刷新 HTML 组件 Angular 6

Refresh HTML Component Angular 6

我正在使用 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 不刷新。 我做了一个将新 ID 传递给 MainComponent 的 EventEmitter,但它仍然无法正常工作,我已经在 AppRoutes onSameUrlNavigation 上尝试过:'reload'.

我做错了什么?是不是reaload所以每个组件都调用它的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) 数据子组件:

public bookId$: Observable<string>;

ngOnInit() {  
    this.bookId$ = this.activatedRoute.paramMap.pipe(
      map((param) => {
        return param.get('BOOK_ID');
      }),
    );
 }

希望对您有所帮助!