簡體   English   中英

如何將 ngOninit 與異步數據一起使用

[英]How to use ngOninit with async data

我在 ngOninit 方法中調用了一個服務方法,並將這個服務方法的返回值分配給一個成員變量。 稍后,我想再次在 ngOnInit 中使用這個變量值。 但是,我想由於同步問題,這個變量沒有分配給某個值 YET,但已經嘗試訪問它的值。 我該如何解決這個問題? 提前致謝

這是我正在使用的 ngOnInit 方法:

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

但它說cannot read property sub of null 。我在登錄帳戶中,我已經嘗試嵌套這兩個調用。 結果是一樣的。

我需要使用switchMapmergeMap嵌套這兩個訂閱調用。 但我不能很好地理解它們的語法。

getUser()服務方法

  public getUser(): Observable<IUser | null> {
    return concat(
      this.getUserFromStorage().pipe(filter(u => !!u), tap(u => 
      this.userSubject.next(u))),
      this.userSubject.asObservable());
  }

getList()服務方法

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

錯誤:

Argument of type '(data: IUser) => void' is not assignable to parameter of type '(value: IUser, index: number) => ObservableInput<any>'.

類型“void”不可分配給類型“ObservableInput”

由於這兩個函數都是異步調用,您可能需要使用switchMap rxjs 運算符以避免處理多個訂閱:


import { switchMap} from 'rxjs/operators';

ngOnInit() {
 this.authorizeService.getUser().pipe(
  switchMap(data => {
   this.service.getList(+data.sub)
})).subscribe( data => this.list = data)
}

您使用的是什么 angular 版本?,如果您顯示代碼以查看更多詳細信息並能夠提供幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM