简体   繁体   中英

How to use ngOninit with async data

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'

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM