I have a 'User' component and its associated service : userService. I would like to use the component form for both new and edit.
the User component is related to several other components (Country and State) and their Services while subscribing to the services subjects.
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);
}
}
User Component 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) => {...}
);
in Edit context (user id in param), I need to order the requests: - get the user - get the states list regarding user.country.id
I then tried something like this :
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(); }
}
);
but it is not working with no error... thank you for your help,