【问题标题】:Angular routerLink does not trigger ngOnInit [duplicate]Angular routerLink 不会触发 ngOnInit [重复]
【发布时间】:2019-09-13 07:23:23
【问题描述】:

这是 componet.ts 文件中的 ngOnInit

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

当我使用[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>

【问题讨论】:

  • 试试这些:&lt;a routerLink="/locations-list"&gt;&lt;a [routerLink]="locations"&gt;
  • 你重定向到同一个页面吗??
  • 从'@angular/core'导入{组件,OnInit};
  • @ram12393 不在同一页面
  • @kashif 已经存在了

标签: angular typescript angular-routerlink


【解决方案1】:

试试这个

// on click call this function
    (click)="HyperLink()"
// on ts file 
    HyperLink(){
       window.open('/locations-list');  
   }

【讨论】:

  • 它有效。但是像href 它比[routerLink]
  • 这是问题的解决方法,而不是问题的真正答案。您将离开 Angular 生命周期。
【解决方案2】:

ngOnInit() 仅在组件实例化后调用一次,但在路由更改时不会调用。您可以注入路由器并订阅它的事件或参数以获取有关路由更改的通知。

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

【讨论】:

  • 你可以尝试添加一个调试器吗?作为 ngOnInit() 中的第一行?
【解决方案3】:

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

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

【讨论】:

  • ngOnInit() { this.route.params.subscribe( params =&gt; { this.locationService.getLocation().subscribe( locations =&gt; { this.locations = locations; }); }); } 我试过这个,但它不起作用。请告诉我上面的代码是对还是错。
  • 有什么错误
  • 不,它和以前一样工作
猜你喜欢
  • 2019-08-11
  • 2018-02-02
  • 2018-04-05
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 2020-01-29
  • 2019-03-29
  • 2019-04-16
相关资源
最近更新 更多