我想通过在我的应用程序的根组件(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加载数据的原因。 (或者我可能以错误的方式接近这个?)
这必须是一个相当普遍的模式,任何有关最佳方法的建议都会有所帮助。谢谢!
答案 0 :(得分:1)
如果这只是一个简单的应用程序,那么上面提出的使用服务的方法将是最好的方法。
另一种方法是使用ngrx查看状态管理。
以下是您将如何进行此操作的示例(未经测试):
// data.ts
import { ActionReducer, Action } from '@ngrx/store';
export const STOREDATA = 'STORE_DATA';
export function dataReducer(state: data = null, action: Action) {
switch (action.type) {
case STOREDATA:
return action.payload;
default:
return state;
}
}
在你应用程序的主模块中,导入这些reducer并使用StoreModule.provideStore(reducers)函数将它们提供给Angular的注入器:
import { NgModule } from '@angular/core'
import { StoreModule } from '@ngrx/store';
import { dataReducer } from './data';
@NgModule({
imports: [
BrowserModule,
StoreModule.provideStore({ data: dataReducer })
]
})
export class AppModule {}
然后在你的AppComponent
中import { Store } from '@ngrx/store';
import { STOREDATA } from './data';
interface AppState {
data: any;
}
export class AppComponent implements OnInit {
constructor(private _myService: MyService, private store: Store<AppState>){ }
ngOnInit() {
this._myService.getSomeData().subscribe(theData => {
this.store.dispatch({ type: STOREDATA, payload: theData });
}, err => {
console.log(err);
});
}
}
在你的孩子组成部分:
import { Store } from '@ngrx/store';
import { STOREDATA } from './data';
interface AppState {
data: any;
}
export class AppComponent implements OnInit {
public data:any;
constructor(private store: Store<AppState>){
this.data = this.store.select('data');
}
}