我正在使用 Angular 6,我有以下组件
MainComponent.ts 在 ngOnInit 上有以下代码:
ngOnInit() {
console.log('OnInit');
this.route.params.subscribe(params => {
if (params['id'] != null) {
this.id= params['id']
}
});
}
然后是 MainComponent.HTML
<DataComponent [id]="id"></DataComponent>
<TableComponent [id]="id"></TableComponent>
<FieldComponent [id]="id"></FieldComponent>
路线是:http://localhost:4200/Data/77
一切都很完美,直到我需要克隆或更改 ID,所以我需要 MainComponent 刷新所有 ID。 我做了以下代码:
this.router.navigate(['/Data', result.id_cloned_data]);
编辑: 路线
const appRoutes: Routes = [
{
path: 'Formula/:idFormula',
component: FormulaMainComponent,
pathMatch: 'full'
},
{ path: 'Formula', component: FormulaMainComponent, pathMatch: 'full' },
{ path: '', component: FormulaMainComponent, pathMatch: 'full' }
];
URL 更改为,例如:http://localhost:4200/Data/399但 MainComponent 不刷新。 我做了一个 EventEmitter 将新 ID 传递给 MainComponent,但它仍然不起作用,而且我已经尝试过 AppRoutes onSameUrlNavigation: 'reload'。
我做错了什么?是不是要重新加载,让每个组件调用其Get from API?
最佳答案
变体 1:
public bookId$: Observable<string> // 'id' is bad name for variable, remember about code readability;
ngOnInit() {
this.bookId$ = this.activatedRoute.paramMap.pipe(
map((param) => {
return param.get('BOOK_ID');
}),
);
}
组件模板:
<DataComponent [bookId]="bookId$ | async"></DataComponent>
<TableComponent [bookId]="bookId$| async"></TableComponent>
<FieldComponent [bookId]="bookId$ | async"></FieldComponent>.
变体 2:
1)DataComponent的模板:
<router-outlet></router-outlet>
2)路由器配置示例:
{
children: [
{
component: DataChildComponent,
path: ':BOOK_ID',
},
],
component: DataComponent,
path: 'Data',
},
3)DataChildComponent的模板:
<DataComponent [bookId]="bookId$ | async"></DataComponent>
<TableComponent [bookId]="bookId$| async"></TableComponent>
<FieldComponent [bookId]="bookId$ | async"></FieldComponent>
4)DataChildComponent:
public bookId$: Observable<string>;
ngOnInit() {
this.bookId$ = this.activatedRoute.paramMap.pipe(
map((param) => {
return param.get('BOOK_ID');
}),
);
}
希望对你有帮助!
关于angular - 刷新 HTML 组件 Angular 6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58371842/