我在我的数据服务中获取了JSON对象值,但是所有组件在我的数据服务加载之前都已加载。因此,当我从组件调用服务方法时,我得到的是不确定的值。
答案 0 :(得分:2)
您可以在数据服务中使用解析器:
resolve
属性。答案 1 :(得分:1)
答案 2 :(得分:1)
我以为您正在使用路由器访问您的页面,因此您可以简单地使用“解析器”功能:RouterLink描述。
path: 'app', component: AppPage, resolve: { myData : DataResolve }
在这里,由于解析器DataResolve,我们要求解析变量“ myData”。 DataResolve是一个简单的Injectable实现Resolve接口:
import { Resolve } from '@angular/router';
import { Injectable } from '@angular/core';
@Injectable()
export class UserResolve implements Resolve<any> {
constructor(private myService: MyService) {}
async resolve() {
const myData= await this.myService.getMyData().toPromise();
return myData;
}
}
然后在解析值时将加载组件。您可以从ActivatedRoute获取数据:
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute {
this.route.data.subscribe(() => {
this.data = this.route.snapshot.data.myData;
});
}
答案 3 :(得分:0)
如果您使用HttpClient获取数据,则需要订阅流,因为它返回可观察的
this.MyService.method().subscribe(value => {
// you can use value here
});
或者您可以在模板中使用异步管道
// controller
value$ = this.MyService.method()
// template
<p>{{value$ | async}}</p>
此外,您可以通过APP_INITIALIZER令牌将服务工厂注册到angular提供商中,并且在初始化应用程序时将执行您的功能。
@NgModule({
...
providers: [
{ provide: APP_INITIALIZER, useFactory: initSomething, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule {}