【发布时间】:2020-11-21 07:53:19
【问题描述】:
我正在创建一个 Angular 9 应用程序。我有一个共享服务,用于在我的组件之间共享用户数据。在我重新加载应用程序之前它工作正常。
我的 sharedService 称为 UserService。该服务设置 BehaviorSubject 的值。在登录时,它调用方法 setLoggedInUser() 从 JWT 获取用户 ID,该用户 ID 存储在 AuthenticationService 中的另一个 BehaviorSubject 中。然后通过 HTTP 调用请求用户的数据。该值设置为 loggedInUser:
export class UserService {
public loggedInUser: BehaviorSubject<User> = new BehaviorSubject<User>(null);
constructor(private http: HttpClient, private authenticationService: AuthenticationService) {
this.setLoggedInUser();
}
async setLoggedInUser() {
const userID: string = await this.authenticationService.userID.pipe(take(1)).toPromise();
const user: User = await this.getUserByID(userID).pipe(take(1)).toPromise();
this.loggedInUser.next(user);
}
getUserByID(id: string): Observable<User> {
return this.http.get<User>(`${this.baseUrl}/${id}`);
}
}
在我的组件中,我在 init 上调用用户数据:
ngOnInit() {
this.userService.loggedInUser.pipe(take(1)).subscribe(user => {
console.log(user);
});
}
在重新加载 UserService 的构造函数时调用 setLoggedInUser() 方法来获取用户。正确接收了用户 ID 和用户数据,但是在从 setLoggedInUserthis.loggedInUser.next(user) 之前调用了组件中的 ngOnInit 方法/em>。这就是我在组件中收到 null 的原因。
我还尝试从我的 app.component 调用 setLoggedInUser(),而不是从 UserService 的构造函数调用它:
export class AppComponent implements OnInit {
constructor(private userService: UserService) { }
async ngOnInit() {
await this.userService.setLoggedInUser();
const user = await this.UserService.loggedInUser.toPromise();
console.log(user);
}
}
但这也显示了我 null。还是和以前一样的问题。
我尝试的另一种没有效果的方法是将 BehaviourSubject 作为 Observable 传递,如此处所述: Behaviour subject value is empty when trying to fetch from a second component
【问题讨论】: