【发布时间】: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。我在登录帐户中,我已经尝试嵌套这两个调用。结果是一样的。
我需要用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”
【问题讨论】:
-
使用
ngOnInit()方法编辑问题。如果您需要更多信息,请告诉我。
标签: asp.net angular typescript asynchronous ngoninit