首页 > 解决方案 > Angular routerLink 不会触发 ngOnInit

问题描述

这是 componet.ts 文件中的 ngOnInit

ngOnInit() {
      this.locationService.getLocation().subscribe( locations => {
      this.locations = locations;
    });
  }
<a [routerLink]="['/locations-list']">

当我使用 a[routerLink]导航到上述组件时,它会导航到该组件并加载视图,但它不会在ngOnInit方法之上触发。但是,如果我刷新页面,它就可以正常工作。
有没有解决上述问题的方法。

我已经习惯href了导航到页面,并且使用href上述方法总是可以正常工作,但速度很慢。这就是为什么我更改href[routerLink].

这是包含视图的 component.html

                <div class="table-responsive">
                  <table class="table">
                    <thead class=" text-primary">
                      <th>
                        Location Name
                      </th>

                    </thead>
                    <tbody *ngIf="locations?.length > 0">
                      <tr *ngFor="let location of locations">
                        <td *ngIf="location.verified != false">
                          {{location.locationName}}
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>

标签: angulartypescriptangular-routerlink

解决方案


当路由器参数更改时,基本路由保持不变。所以它不会触发ngOnInit. 所以订阅路由事件

ngOnInit() {
     this.route.params.subscribe(
     params => { 
            // your code
     });
  }

推荐阅读