【问题标题】:Refresh HTML Component Angular 6刷新HTML组件Angular 6
【发布时间】:2019-10-14 07:22:40
【问题描述】:

我正在使用 Angular 6,并且我有以下组件

在 ngOnInit 上有此代码的 MainComponent.ts:

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'。

我做错了什么?不是要重新加载,所以每个组件都从 API 调用它的 Get 吗?

【问题讨论】:

  • 如果将 console.log(this.id) 放入 subscribe() 会发生什么?
  • @MaciejWójcik 它刷新 .TS 中的变量,但不刷新 HTML
  • 是的,因为路由器只创建了一次参数。可能更好的选择使用 这个组件。并检查孩子级别的身份证?记住 的级别和参数 'id'
  • 我尝试在所有子组件上调用 subscribe Params 并且它可以工作,但我想它不是一个“好代码”,我认为我在使用提供 ID 的主要组件做正确的事情到子组件并自行重新加载,但它并没有像我想象的那样工作

标签: angular angular-ui-router angular6


【解决方案1】:

变体 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');
      }),
    );
 }

希望对你有帮助!

【讨论】:

  • 谢谢,但仍然无法正常工作,第一次通话时一切正常,但是当我更改 ID 时仍然无法正常工作,我会尝试像你所说的那样
  • 请显示您的路由器配置,看起来有问题。
  • 更新了我的答案。检查第二个变体
  • 我更新了我的问题,要试试你的第二个变种
  • 激活的路由器是两个斜杠之间的 url 的一部分。组件消耗了这个激活的路由。记住层次结构。 'parent_url/child_url/' 等等,所以你的组件应该是相同的层次结构 ParentComponent -> Child Component。 (对不起我的英语,希望对你有帮助)
猜你喜欢
  • 2019-07-17
  • 1970-01-01
  • 2018-08-03
  • 2019-06-12
  • 2019-02-14
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 2019-04-01
相关资源
最近更新 更多