angular - 刷新 HTML 组件 Angular 6

标签 angular angular-ui-router angular6

我正在使用 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/

相关文章:

c# - 删除对 ASP.NET Core ApiController 的请求不起作用

javascript - 向 Observable 发射新值

angularjs - 用户界面路由器 : How to validate parameter before state resolves

angular - 在 Angular 中显示 formControlName 的验证消息

javascript - ngx-editor 链接重定向到与 Angular 项目 url 相结合的 url

angular - 获取作为 Angular 组件的 DOM 元素

javascript - Angular 7 - 上传多个文件以及数据和报告进度

angularjs - Angular UI Router : inherit only URLs (using parent. 子状态)没有嵌套 View

angularjs - ui.router 和 ui.state 之间的 angularJS 有什么区别?

angular - 如何从 Angular 规范触发输入 onchange