Within the ngOnInit method, I am calling a service method and assigning the return value to a member variable. However, when trying to access this variable later in the ngOnInit again, it seems that due to synchronization issues, the value has not been assigned yet. How can I resolve this problem? Thank you for your help.
This is the implementation of the ngOnInit method:
ngOnInit() {
// Retrieve the user Id by executing a service method.
this.authorizeService.getUser().subscribe(data => {
this.userId = +data.sub;
});
// Obtain the list associated with the user by passing the userId as a parameter.
this.service.getList(this.userId).subscribe(data => {
this.list = data;
})
}
An error message stating cannot read property sub of null
appears. Despite nestling these two calls and being logged into the account, the issue persists.
I have attempted to nest the subscriptions using switchMap
or mergeMap
, but I am struggling with their syntaxes.
The getUser()
service method:
public getUser(): Observable<IUser | null> {
return concat(
this.getUserFromStorage().pipe(filter(u => !!u), tap(u =>
this.userSubject.next(u))),
this.userSubject.asObservable());
}
The getList()
service method:
getList(userId: number): Observable<number[]> {
return this.http.get<number[]>("myApiURLhere?userId=" + userId)
.pipe(
retry(1),
catchError(this.errorHandler)
);
}
Error details:
Argument of type '(data: IUser) => void' is not assignable to parameter of type '(value: IUser, index: number) => ObservableInput<any>'.
Type 'void' is not assignable to type 'ObservableInput'