[英]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
。我在登录帐户中,我已经尝试嵌套这两个调用。 结果是一样的。
我需要使用switchMap
或mergeMap
嵌套这两个订阅调用。 但我不能很好地理解它们的语法。
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.