将数据从根(app)组件传递到路由组件

Pass data from Root (app) Componenet to route component

我想通过在我的应用程序的根组件 (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 加载数据的原因。 (或者我可能以错误的方式处理这个问题?)

这一定是一个相当常见的模式,任何有关处理此问题的最佳方法的建议都会有所帮助。谢谢!

如果这只是一个简单的应用程序,那么上面建议的使用服务将是最好的方法。

另一种方法是使用 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');
   }
}