Angular8 路由:强制所有 children 到 运行 它们的构造函数 ngOnInit
Angular8 routing : force all children to run their constructor, ngOnInit
我有以下路由:
const routes: Routes = [
{
path: '', children: [
{path: '', pathMatch: 'prefix', redirectTo: 'timing'},
{path: 'timing', component: TimingComponent},
{path: 'fio', component: FioComponent},
{path: 'rsp', component: RspComponent},
]
}
];
我有一个打开文件的全局服务,必须向所有 children 显示该文件中的数据。
但此时,只有'timing'还活着。 '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);
})
但这不起作用。
提前谢谢你,
兹维卡
这就是将 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
}
}
我有以下路由:
const routes: Routes = [
{
path: '', children: [
{path: '', pathMatch: 'prefix', redirectTo: 'timing'},
{path: 'timing', component: TimingComponent},
{path: 'fio', component: FioComponent},
{path: 'rsp', component: RspComponent},
]
}
];
我有一个打开文件的全局服务,必须向所有 children 显示该文件中的数据。 但此时,只有'timing'还活着。 '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);
})
但这不起作用。
提前谢谢你, 兹维卡
这就是将 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
}
}