【发布时间】:2021-02-16 00:44:17
【问题描述】:
我正在为一个简单的概念而苦苦挣扎,我可以在 C# 中轻松实现,但在 Angular 中却不行。
我正在尝试将用户配置文件存储在我在每个组件中添加的服务中,因此每次加载/显示组件时我都不会获取配置文件。
所以,我创建了一个服务,其中构造函数获取用户配置文件,并将其保存在一个变量中,并为我的所有组件使用一个 getter。
我遇到的问题是,当组件调用 getter 时,变量尚未设置,因为服务尚未响应。这会导致未定义的错误并破坏组件,因为配置文件在组件的代码中至关重要。
在 C# 中,我会在获取配置文件时简单地放置 1 等待,以便其他一切都可以运行而无需等待,因为我知道数据在那里。
但在 Angular 中,我尝试过,但它似乎不起作用。
export class SharedService {
private userProfile;
constructor(private http: HttpService) {
this.initProfile();
}
async initProfile(): Promise < void > {
this.userProfile =await this.http.getProfile().subscribe((data: any) => {
//...
}
});
getUserProfile() {
return this.userProfile;
}
}
getprofile:
getProfile() {
return this.shttp.get(environment.apiEndpoint + 'Getprofile/', {
headers: new HttpHeaders({
'Content-Type': 'application/json',
Accept: '*/*'
})
});
}
在组件中,当我调用 getUserProfile 函数时,服务会立即使用空的 userProfile 进行响应。
编辑: 我设法通过非常讨厌的代码 sn-p 获得所需的行为,但这应该清楚我要完成的工作。在我的 profile.component.ts 中:
async ngOnInit(): Promise<void> {
while (this.profile == null) {
await this.sharedService.sleep(500);
this.profile = this.sharedService.getUserProfile();
}
if (this.profile.isadmin){
this.CalculateStuff();
}
//
//imagine here even more code using the this.profile variable in if statements,
//cases, etc.
//
}
睡眠功能
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
我必须编写一个睡眠函数来实现这一点,这对我来说是一个明确的信号,表明我做错了。这就是我在这里的原因。
【问题讨论】:
-
如果你喜欢使用 Promise,请将 observable 转换为 Promise:
this.userProfile =await this.http.getProfile().toPromise();应该更好 -
您不能
await订阅或可观察并获得结果值,这仅适用于承诺。您可以按照@Andrei 的建议使用.toPromise,或者使用RxJS(Angular 的大部分内容都基于可观察对象,我建议使用后者)。
标签: angular