简体   繁体   English

如何将 ngOninit 与异步数据一起使用

[英]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.我在 ngOninit 方法中调用了一个服务方法,并将这个服务方法的返回值分配给一个成员变量。 Later on, I want to use this variable value inside the ngOnInit again.稍后,我想再次在 ngOnInit 中使用这个变量值。 But, I suppose due to synchronization issues, this variable is not assigned to the some value YET, but tried to access its value already.但是,我想由于同步问题,这个变量没有分配给某个值 YET,但已经尝试访问它的值。 How can I fix this problem?我该如何解决这个问题? Thanks in advance提前致谢

This is the ngOnInit method I m using:这是我正在使用的 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;
    })
  }

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.但它说cannot read property sub of null 。我在登录帐户中,我已经尝试嵌套这两个调用。 Result is the same.结果是一样的。

I need to nest these two subscriptions call with switchMap or mergeMap .我需要使用switchMapmergeMap嵌套这两个订阅调用。 But I could not understand their syntaxes very well.但我不能很好地理解它们的语法。

getUser() service method getUser()服务方法

  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()服务方法

  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'类型“void”不可分配给类型“ObservableInput”

As both functions are asynchronous call, you might want to use switchMap rxjs operator in order to avoid to deal with multiple subscriptions:由于这两个函数都是异步调用,您可能需要使用switchMap rxjs 运算符以避免处理多个订阅:


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您使用的是什么 angular 版本?,如果您显示代码以查看更多详细信息并能够提供帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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