我有一些使用可觀察原則的服務。我想在決議器中獲取 2 個服務的結果以在我的頁面上使用。但是頁面內的結果只是一個空的資料物件。我也試過first()代替take(1),但沒有區別。
我的決議器:
@Injectable({
providedIn: 'root'
})
export class CompanyResolver implements Resolve<any> {
constructor(private companyResolver: CompanyService, private countryService: CountryService, private genderService: GenderService) { }
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
) {
return forkJoin({
countries: this.countryService.getCountries().pipe(take(1)),
genders: this.genderService.getGenders().pipe(take(1)),
});
}
}
我的頁面:
export class SettingsCompanyOverviewComponent implements OnInit {
constructor(
public countryService: CountryService,
private route: ActivatedRoute
) {
console.log(this.route.snapshot);
}
ngOnInit(): void {
}
}
服務:
export class CountryService {
private countryObserver$: BehaviorSubject<CountryInterface[]> = new BehaviorSubject([]);
constructor(
private apiService: ApiService
) {
this.getData();
}
getCountries(): Observable<GenderInterface[]> {
return this.countryObserver$.asObservable();
}
private getData(): void {
this.apiService.get<CountryInterface[]>(ApiRoutes.getCountries, null).then(res => {
this.countryObserver$.next(res);
});
}
}
我不明白出了什么問題,因為我真的希望這兩種服務都有資料。
編輯:似乎來自 observable 的第一個資料是空的,之后我得到了預期的結果。我認為這BehaviorSubject會回傳最后的結果?
uj5u.com熱心網友回復:
正如評論中所建立的那樣,BehaviorSubject 在決議器中發出初始值,因為 http 請求需要一些時間才能完成,但是到那時,當發出新值時,決議器已經完成了它的作業。
在我看來,您不需要將 behaviorSubject 作為中間人?您可以將它直接分配給一個可觀察的物件。如果您需要共享相同的資料,您可以使用shareReplaywhich 只發出值而不發出 http 請求。所以對于國家服務來說是這樣的:
export class CountryService {
constructor(
private apiService: ApiService
) { }
countries$ = this.getData().pipe(shareReplay());
private getData(): Observable<CountryInterface[]> {
return this.apiService.get<CountryInterface[]>(ApiRoutes.getCountries, null)
}
}
然后在您的決議器中,只聽countries$而不是您的 BehaviorSubject。
return forkJoin({
countries: this.countryService.countries$.pipe(take(1)),
//....
});
您可以像我在上面為國家/地區服務所做的那樣將相同的內容應用于其他服務。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/379937.html
標籤:有角的
