【问题标题】:Angular:9 How to change variable from another sibling component?Angular:9 如何从另一个兄弟组件更改变量?
【发布时间】:2020-05-20 11:40:50
【问题描述】:

我在 Component1 中更新字符串变量时遇到问题,我更改了 Component2 中的值。

组件是相互独立的。 Component1 的 HTML 模板中的值不会自行更新。

有没有办法强制更新模板?除此之外,我还尝试过:订阅、@Input/@Output - 但我可能会以错误的方式这样做。除此之外,我认为我不能在模板(comp2)中包含选择器,因为它会在component1中显示来自component2的html模板。 我希望我错了。请引导我摆脱我的错误。

说明图:

【问题讨论】:

  • 你们俩都是对的。文章对我帮助很大!非常感谢。

标签: angular typescript data-binding


【解决方案1】:

看看Behavior Subject

// RxJS v6+
import { BehaviorSubject } from 'rxjs';

const subject = new BehaviorSubject(123);

// two new subscribers will get initial value => output: 123, 123
subject.subscribe(console.log);
subject.subscribe(console.log);

// two subscribers will get new value => output: 456, 456
subject.next(456);

// new subscriber will get latest value (456) => output: 456
subject.subscribe(console.log);

// all three subscribers will get new value => output: 789, 789, 789
subject.next(789);

// output: 123, 123, 456, 456, 456, 789, 789, 789

【讨论】:

    【解决方案2】:

    你在正确的轨道上。如果不是组件之间的父子关系,那么看@Input就没有意义了。

    如果只是需要在兄弟组件中显示的数据,那么使用一个服务并在html中绑定。看这篇博文:https://medium.com/@nodexperts_88267/data-transfer-one-component-to-another-angular-7-c076272c78e1

    但是如果您还需要根据更改做一些事情,那么BehaviorSubject 是可行的(Soham 的回答)。

    【讨论】:

      猜你喜欢
      • 2019-12-09
      • 2017-10-21
      • 2014-07-12
      • 2016-06-14
      • 2019-11-22
      • 2017-04-01
      • 2017-02-14
      • 1970-01-01
      • 2021-11-25
      相关资源
      最近更新 更多