0

I am calling a service method inside the ngOninit method and assign this service method's return value to a member variable. Later on, I want to use this variable value inside the ngOnInit again. But, I suppose due to synchronization issues, this variable is not assigned to the some value YET, but tried to access its value already. How can I fix this problem? Thanks in advance

This is the ngOnInit method I m using:

ngOnInit() {

    //Execute a service method here to get the user Id.
    this.authorizeService.getUser().subscribe(data => {
      this.userId = +data.sub;
    });

    //Pass the userId as a parameter to get the list associated with that user.
    this.service.getList(this.userId).subscribe(data => {
      this.list = data;
    })
  }

But it says that cannot read property sub of null.I am in the logged in account and I have already tried to nest these two calls. Result is the same.

I need to nest these two subscriptions call with switchMap or mergeMap. But I could not understand their syntaxes very well.

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());
  }

getList() service method

  getList(userId: number): Observable<number[]> {
    return this.http.get<number[]>("myApiURLhere?userId=" + userId)
      .pipe(
        retry(1),
        catchError(this.errorHandler)
      );
  }

Error:

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'

zodiac645
  • 191
  • 1
  • 3
  • 14

2 Answers2

0

As both functions are asynchronous call, you might want to use switchMap rxjs operator in order to avoid to deal with multiple subscriptions :


import { switchMap} from 'rxjs/operators';

ngOnInit() {
 this.authorizeService.getUser().pipe(
  switchMap(data => {
   this.service.getList(+data.sub)
})).subscribe( data => this.list = data)
}
Gérôme Grignon
  • 3,859
  • 1
  • 6
  • 18
0

What angular version are you use ?, if you Show the code for see more details and to be able to help