【问题标题】:How to recall component controller in Angular 4 for the same route link?如何在 Angular 4 中为相同的路由链接调用组件控制器?
【发布时间】:2018-01-05 11:27:26
【问题描述】:

我有两个路由链接:

/article/1
/article/2

这些链接与同一个组件相关:

{path: 'article/:id', component: HomeComponent}

当组件初始化后,点击链接/article/2后不会再次初始化该组件。

如何解决?

HTML 是:

 <div (click)="setCurrentRole(role)" *ngFor="let item of menuService.getMenuItems(role)"><a
                [routerLink]="[item.url]" (click)="setActiveLink(i, item.url)" [routerLinkActive]="['is-active']">{{item.title
                | translate}}</a></div>

【问题讨论】:

    标签: angular angular2-routing angular4-router


    【解决方案1】:

    重新加载组件:

    在你的组件中,在 init 钩子上,订阅路由事件,并将你的 init 代码移动到一个函数中

    constructor(private route: ActivatedRoute) {}
    
    ngOnInit() {
      this.route.params.subscribe(params => {
        console.log(params['id']);
        this.doOnInit();
      });
    }
    
    doOnInit() {
      // your old code here
    }
    

    订阅路由器事件:

    constructor(private router: Router) {}
    
    ngOnInit() {
      this.router.events.subscribe(events => {
        // Several routing events, take only the last one
        if (events instanceof NavigationEnd || events.constructor.name === NavigationEnd.name) {
          console.log(params['id']);
          this.doOnInit();
        }
      });
    }
    
    doOnInit() {
      // your old code here
    }
    

    【讨论】:

    • 另一种方式?不适合我
    • 我用这个:&lt;div *ngFor="let item of menuService.getMenuItems(role)"&gt;&lt;a [routerLink]="[item.url]" [routerLinkActive]="['is-active']"&gt;{{item.title | translate}}&lt;/a&gt;&lt;/div&gt;
    • 我做了一个实验:ngOnInit() { console.log("ok") } ; 第二次点击后它没有显示ok
    • 你订阅了路由事件吗?
    • 不,有必要吗?我以为每次都会调用构造函数
    【解决方案2】:

    您只对您在 url 中更改的 id 感兴趣 那么你可以做类似的事情

        id: number;
    
      constructor(private route: ActivatedRoute){}
    
      ngOnInit() {
        this.id = +this.route.snapshot.params['id'];
        this.route.params.subscribe(
          params => {
            /// this method will called if you navigate to different id
            this.id = +params['id'];
          }
        )
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      • 1970-01-01
      • 2012-09-21
      • 2021-05-26
      • 1970-01-01
      相关资源
      最近更新 更多