【问题标题】:How to use ngOninit with async data如何将 ngOninit 与异步数据一起使用
【发布时间】:2020-09-22 16:33:49
【问题描述】:

我在 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”

【问题讨论】:

  • 使用ngOnInit() 方法编辑问题。如果您需要更多信息,请告诉我。

标签: asp.net angular typescript asynchronous ngoninit


【解决方案1】:

您使用什么角度版本?,如果您显示代码以查看更多详细信息并能够提供帮助

【讨论】:

  • Angular CLI: 8.0.6
  • 尝试 ngAfterViewInit 并调试 data.sub 可能响应结构不同
【解决方案2】:

由于两个函数都是异步调用,你可能需要使用 switchMap rxjs 操作符以避免处理多个订阅:


import { switchMap} from 'rxjs/operators';

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

【讨论】:

  • 我已经尝试像你说的那样嵌套订阅调用,如果这就是你的意思,但没有锻炼。
  • 你确定你的语法是正确的?我收到一些类型错误
  • 你在哪里得到这些错误?我会考虑检查 +data.sub 是否具有正确的类型作为 getList() 的参数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-16
  • 2013-09-11
  • 2019-11-05
  • 2019-08-20
  • 1970-01-01
  • 2013-08-14
相关资源
最近更新 更多