【问题标题】:Angular2: Rendering the same component with different idsAngular2:使用不同的ID渲染相同的组件
【发布时间】:2017-03-14 16:12:42
【问题描述】:

我有一个普通的顶栏,上面有几个按钮。按钮路由到具有不同参数的相同组件dashboard。我想读取该参数并对仪表板进行更改。
在仪表板上,我只是根据从顶栏按钮传递的参数更新 iframe 的源 URL。
一旦仪表板组件第一次加载,当从顶部栏中单击按钮时,constructor()、ngOnit 或 ngOnChange 不会被调用。 这是代码:
app.component.html

    <button md-button  [routerLink]="['/dashboard', 'first']"  id="first" class="top-link">First</button>
    <button md-button  [routerLink]="['/dashboard', 'second']" id="second" class="top-link">second</button>
    <button md-button  [routerLink]="['/dashboard', 'third']" id="third" class="top-link">third</button>

dashboard.component.ts

constructor(private route: ActivatedRoute, private sanitizer: DomSanitizer) {
    this.dashboardId = route.snapshot.params['id'];
    console.log("Constructor "+route.snapshot.params['id']);
    this.dashboardUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.first_url);
  }

  ngOnInit() {
    console.log("OnInit "+this.route.snapshot.params['id']);
    //this.dashboardUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.first_url);
  }

如何将按钮 id 从顶部栏传递到仪表板组件并刷新页面?

【问题讨论】:

  • 构造函数在第一次加载时被调用,但在你点击仪表板右侧的 'dashboard/:id' 路由时不会调用?
  • constructor()、ngOnit 或 ngOnChange 在从顶部栏中单击按钮时不会被调用这是什么意思?
  • @YounesM 我得到了那个部分。然后调用哪个生命周期方法?是否有另一种方法可以将按钮 id 从 app.component.html 传递到 dashboard.component?
  • @Aravind 是的。这就是我的意思。
  • 被点击时不被调用是否有意义。

标签: javascript angular typescript


【解决方案1】:

这是正常行为。 您可以订阅路由更改并相应地更新组件:

ngOnInit(): void {
    this.changeMeOnUpdate();
}

changeMeOnUpdate(){
    this.sub = this.activatedRoute
        .params
        .subscribe(params => {
            //do what you want with your params and update the component
        }
}

【讨论】:

  • 谢谢。 this.sub 这里是什么?我是 RxJS 的新手。
  • rxjs Subscription import { Subscription } from 'rxjs/Subscription'; 可以在组件销毁时使用它的引用取消订阅,防止内存泄漏this.sub.unsubscribe();
  • 很奇怪......如果你能提供一个能重现你的问题的plunker,我会看看。
猜你喜欢
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多