Angular8路由:强制所有子代运行其构造函数ngOnInit

问题描述 投票:0回答:1

我有以下路由:

const routes: Routes = [
  {
    path: '', children: [
      {path: '', pathMatch: 'prefix', redirectTo: 'timing'},
      {path: 'timing', component: TimingComponent},
      {path: 'fio', component: FioComponent},
      {path: 'rsp', component: RspComponent}, 
    ]
  }
];

我有一个全局服务,该服务打开一个文件,并且必须向所有子项显示此文件中的数据。但是在这一点上,只有“定时”是活的。 'fio','rsp'未定义。

是否有可能使'fio','rsp'也运行?在全球服务中,我尝试过:

this.router.navigate(['/timing']).then(()=>{
        this.timing.UpdateView (val.Root.Timing);
        this.router.navigate (['fio']).then (()=>{ 
          this.fio.UpdateView (val.Root.Fio);
        })

但是这不起作用。

谢谢你,兹维卡

angular routing
1个回答
0
投票

这是将some.service.ts文件下载的数据注入多个组件的方式。

app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [MyService], // provide service
  bootstrap: [AppComponent]
})
export class AppModule { }

服务只是在内部创建变量以在其中保存数据的示例。

my.service.ts

@Injectable()
export class MyService {

    data: Observable<any>

    getData() {
        this.data = this.http.get() // http call to get data or other way to get data.
    }
}

app.component.ts

export class AppComponent {

  constructor(private myServ: MyService) {}

  ngOnInit() {
    this.myServ.getData() // Calling function to load data
  }
}

子组件示例:

export class FioComponent {

  data$: Observable<any>

  constructor(private myServ: MyService) {} // when injecting service there have to be private, public or protected statement.

  ngOnInit() {
    this.data$ = this.myServ.data
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.