我有一个“用户”组件及其相关服务:userService。我想将组件表单用于新建和编辑。
订阅服务主题时,用户组件与其他几个组件(国家和州)及其服务相关。
export class CountrystateService {
private countries: Country[] = [];
private countriesSubject = new Subject<Country[]>();
countriesSubject$ = this.countriesSubject.asObservable();
private allStates: State[];
private states: State[];
private statesSubject = new Subject<State[]>();
statesSubject$ = this.statesSubject.asObservable();
constructor(private apiService: ApiService) { }
getCountriesAllStatesFromRest() {
forkJoin({
countries: this.apiService.getEntriesFromRest('countries').pipe(
tap((countries: Country[])=> {this.countries=countries;})),
states: this.apiService.getEntriesFromRest('countries').pipe(
tap((states: State[])=> {this.allStates=states;}))
}).subscribe(
(results) => {
this.countriesSubject.next(this.countries.slice());
},
(error) => {
this.countriesSubject.next(error);
return throwError(error);
},
() =>{}
)
}
filterStatesForCountry(countryId?) {
if (countryId) {
this.states=this.allStates.filter(item => +item.country.split('/').pop() === countryId);
this.statesSubject.next(this.states);
}
}
用户组件 ngOnInit:
ngOnInit() {
this.stateSubscription = this.countrystateService.statesSubject$.subscribe(
(states: State[]) => {
if (states) {
this.states = states;
this.FooFunction();
}
},
(error) => {..}
);
this.countrySubscription = this.countrystateService.countriesSubject$.subscribe(
(countries: Country[]) => {
if (countries) {
this.countries = countries;
}
},
(error) => {...}
);
this.userSubscription = this.userService.userSubject$.subscribe(
(user: User=> {
if (user) {
this.user = user;
}
},
(error) => {...}
);
在编辑上下文(参数中的用户 ID)中,我需要订购请求: - 获取用户 - 获取有关 user.country.id 的状态列表
然后我尝试了这样的事情:
this.userIdSubscription = this.route.paramMap.subscribe(
(params: ParamMap) => {
const userId = +params.get('id');
if (userId) {
...
this.userService.getUserFromRest(userId);
this.countrystateService.getCountriesAllStatesFromRest();
forkJoin({
user: this.userService.userSubject$,
states: this.countrystateService.statesSubject$,
}).pipe(
tap(results => console.log('FORKJOIN TRIGGERED')),
tap(results => {
...
this.countrystateService.filterStatesForCountry(results.user.country.id);
}),
);
}
else { this.countrystateService.getCountriesAllStatesFromRest(); }
}
);
但它不能正常工作...谢谢您的帮助,