【问题标题】:ngOnInit not called when same component is loaded with different data当同一个组件加载不同的数据时,不会调用 ngOnInit
【发布时间】:2017-02-19 03:29:39
【问题描述】:

我有一个 Angular 2 应用程序,我使用路由器在视图之间导航,就像其他人一样。这是我的特定组件路径的样子:

{
    path: 'home/view1/:viewID',
    component: ViewComponent,
    children: [
        { path: 'pane/:paneId/section/:sectionId', component: SectionEditComponent },
        { path: '**', component: ViewEditComponent }
    ]
},

现在,我在 ViewComponent 上有两个按钮,用于为 section1 和 section2 加载 SectionEditComponent。

路径 1:pane/1/section/1
路径2:pane/1/section/2

ViewComponent 模板:

   <div class="col-md-8" style="background-color: white; height: 100%">
       <button (click)="loadPath(1)">Path1</button>
       <button (click)="loadPath(2)">Path2</button>
       <router-outlet></router-outlet>
   </div>

现在,当我在同一个 ViewComponent 中从 Path1->Path2 或 Path2->Path1 导航时,不会调用 ngOnInit(),因此不会加载新路径,即使 url 实际上会根据新的部分 ID 发生变化。

这是已知的还是预期的行为?有什么我做错了吗?

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

    注入路由并订阅参数变化

    constructor(route:ActivatedRoute) {
      route.params.forEach(params => {
        myInit(params['paramId']);
      });
    }
    

    【讨论】:

    • 这是好的做法吗?你不应该subscribe 给参数还是会给出同样的问题?你知道为什么onSameUrlNavigation: 'reload' 似乎也没有解决它吗?
    【解决方案2】:

    只是想补充一点,如果您使用路由解析器在组件加载之前获取数据,那么您可以将以下代码放入组件的 ngOnInit 方法中:

    ngOnInit(){
        this.activatedRoute.data.subscribe(data => {
             initData(data['mydata']);
        });
    }
    
    initData(data){
        // process new data
    }
    

    现在,每当您的解析器更新路由的解析数据时,您的组件模型都会更新并显示新数据。

    【讨论】:

      【解决方案3】:

      对于组件的同一个实例,ngOnInit() 只被调用一次。

      【讨论】:

      • 谢谢,那么如何实现reload呢? (或者如果每次都调用任何其他方法)
      • 但是你到底想达到什么目的呢?
      • 其实我有一个基于路由参数的组件初始化逻辑。 @Günter Zöchbauer 的答案正是我想要的 (stackoverflow.com/a/39962929/6950218)
      【解决方案4】:

      我遇到了类似的问题,在路由更改时未调用 ngOnInit。 我将代码移到 ngAfterViewInit() 并成功了。

      【讨论】:

      • 我在执行此操作时收到了Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.。此外,在重用组件时它没有触发两次,所以我不确定它是否有效。
      • @TetraDev 这可能会对您有所帮助:stackoverflow.com/questions/34364880/…
      猜你喜欢
      • 1970-01-01
      • 2019-06-22
      • 2017-05-31
      • 2016-10-19
      • 2021-06-27
      • 2017-12-03
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多