我对Angular/typescript相对陌生,并有以下问题。对你们大多数人来说可能很琐碎。在我的ngOnInit()
中,我试图通过GET请求检索存储在后端的设置。之后,我需要开始订阅一个可观察的。可观察到的是开始填充小部件(内容/它们随着时间的推移而变化(,而设置则为我提供了将显示的小部件的数量/类型。
基本上,让ngOnInit((等待getGeneralSettingsOnce
响应,然后启动一些其他订阅。
我的请求功能:
getGeneralSettingsOnce(): Promise<any> {
return this.http.get(`${environment.API_URL}/get_general_settings`).toPromise()
.then(response => {
return response
})
}
我的第一次尝试是将主页面的ngOnInit设置为异步函数,然后等待承诺->这导致了我主页中一些静态小部件的Cannot read properties of undefined (reading '-1')
。根据我读到的一篇文章,这可能是因为我的主页没有完全加载,而浏览器已经在尝试渲染页面?(不确定(来源:文章
主页的ngOnInit的部分
async ngOnInit() {
let generalSettings = await this.localService.getGeneralSettingsOnce(); //calling the promise
this.widgetCount = generalSettings.widget_count
// other subsrciptions
this.localService.getWidgetContent().subscribe(
data => { this.loadWidgetContent(data)
}
}
}
所以我的问题是,我如何归档我的目标,首先初始化设置,然后像同步一样订阅其他请求函数。最好不要出错。
您可以选择subscribe
(从可观察对象获取数据的常用方法(与switchMap
相结合,它可以执行一个又一个可观察对象!
subscription: Subscription = new Subscription(); // <- stores observables to unsubscribe
ngOnInit() {
this.subscription.add( // <- add the subscription to a single place
this.localService
.getGeneralSettingsOnce()
.pipe(
switchMap(generalSettings => {
this.widgetCount = generalSettings.widget_count;
// other subsrciptions
return this.localService.getWidgetContent();
})
)
.subscribe(data => {
this.loadWidgetContent(data);
})
);
}
ngOnDestroy() {
this.subscription.unsubscribe(); // <- subscribers must be unsubscribed to prevent memory leaks
}