【问题标题】:Angular 4 component reference into another componentAngular 4组件引用到另一个组件
【发布时间】:2018-06-28 01:20:00
【问题描述】:

我有一个关于 Angular 4 的一般问题。

我的一位同事创建了AComponent 的引用并将其作为属性绑定到BComponent 以访问AComponent 的属性,而不是单独绑定AComponent 的属性。然后他还订阅了 AComponent 中的一个 observable。

这是一个想法:

// a.component.ts
@Component({
  selector: 'some-a',
  template: `<some-b [someRefToAComponent]="someRefToThis">...</some-b>`
})
export class AComponent {
  someRefToThis = this;
  someObservable: Observable<any>;
}

// b.component.ts
@Component({
  selector: 'some-b',
  template: `...`
})
export class BComponent {
  @Input() someRefToAComponent: AComponent;
  someSubscription: Subscription<any>;

  ngOnInit() {
    this.someRefToAComponent.someObservable.subscribe(...);
  }

  ngOnDestroy() {
    this.someSubscription.unsubscribe();
  }
}

这是我的问题:这是一种不好的做法还是非常不好的做法?另外:在这种情况下会发生什么?会不会导致内存泄露?

知道会发生什么会很有趣,因为我对 Angular 的内部功能还没有深入的了解。

【问题讨论】:

  • 根据最终目标,肯定有更好的方法来实现这种效果。在我看来,为什么 Angular 没有抱怨循环依赖似乎很奇怪。
  • 材质日期选择器以类似的方式绑定到输入字段。在这种情况下,输入字段的功能与日期选择器组件的存在紧密耦合,因此在两者之间放置服务将是不必要的间接。看这里github.com/angular/material2/blob/master/src/lib/datepicker/…
  • 编程中始终没有灵丹妙药。只要您考虑自己的决定并以批判性的方式评估其他方法,一切都很好。
  • @Jota.Toledo 是的,但是您可以对父元素的构造函数添加一个可选的依赖项......这不是实现这种效果的好方法

标签: angular angular-components


【解决方案1】:

最终,当谈到以 Angular 方式做事时,我会认为这是“违背常规的”。听起来您真正需要的是服务。需要从多个端点交互和访问的数据,无论是组件还是模块,都应该包含在服务中。

另一种选择是使用Data Binding在组件之间传递数据。

这就是真正需要了解 Angular 中的依赖注入系统的地方。服务旨在成为允许组件与类似数据交互的应用程序单例。

我真的建议您查看有关Dependency Injection 的文档。

【讨论】:

    猜你喜欢
    • 2016-08-16
    • 2018-03-23
    • 2018-04-14
    • 2018-08-13
    • 2018-05-31
    • 2018-05-31
    • 2018-02-20
    • 2017-12-31
    • 1970-01-01
    相关资源
    最近更新 更多