我想通过在我的应用程序的根组件(AppComponent)中使用服务调用来进行API调用 . 结果数据需要由一个或多个由RouterModule控制的其他(子)组件显示 . 例如:
export class AppComponent implements OnInit {
constructor(private _myService: MyService){ }
ngOnInit() {
this._myService.getSomeData().subscribe(theData => {
// theData needs to be displayed in ChildComponenet1 and / or ChildComponent2
}, err => {
console.log(err);
});
}
}
我的AppModule使用RouterModule设置路由:
@NgModule({
declarations: [
AppComponent
],
imports: [
RouterModule.forRoot([
{ path: 'child-component-1', component: ChildComponent1 },
{ path: 'child-component-2', component: ChildComponent2 },
]),
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
我希望每次用户导航到/ child-component时都避免发出http请求,这就是我需要从AppComponent加载数据的原因 . (或者我可能以错误的方式接近这个?)
这必须是一个相当普遍的模式,任何有关最佳方法的建议都会有所帮助 . 谢谢!
1 回答
如果这只是一个简单的应用程序,那么上面建议使用服务将是最好的方法 .
另一种方法是使用ngrx查看状态管理 .
以下是您将如何操作的示例(未经测试):
在应用程序的主模块中,导入这些reducers并使用StoreModule.provideStore(reducers)函数将它们提供给Angular的注入器:
然后在你的AppComponent中
在你的子组件中: