简体   繁体   English

Angular6:控制应用程序内部的数据共享

[英]Angular6: control data sharing inside application

In my Angular application, I have the subscription in every single component for watching if the user's Company change. 在我的Angular应用程序中,我在每个组件中都有订阅,用于监视用户的Company发生了变化。 On app init I download user's Company , so subscription fires once in every component I'm subscribing for changes in the state of the company (it's necessary because I am using this Company data in most of them). 在应用程序初始化中,我下载了用户的Company ,因此在我要订阅公司状态更改的每个组件中都会触发一次订阅(这是必要的,因为我在大多数组件中都使用了Company数据)。 One of my components have a subscription to Company , and it downloads data once on init. 我的组件之一已订阅Company ,并且它在init一次下载了数据。 When I change the view, a subscription is no more fired, so I need to download data. 当我更改视图时,不再触发订阅,因此我需要下载数据。 Code looks like 代码看起来像

    this.subscription = this
    .companyService
    .CompanyState
    .subscribe((company: Company) => {
        this.getSomeData()
    })
    this.getSomeData()

I've tried adding some flag like needDownload with default value true, and set it to false if subscription fires this.getSomeData() , but it's async and doesn't work very well. 我尝试添加一些标记,如needDownload ,其默认值为true,如果订阅触发了this.getSomeData() ,则将其设置为false,但是它是异步的,效果不佳。 If I remove the subscription from this component, I will stop watching changes on Company state. 如果我从该组件中删除订阅,则将停止观看“ Company状态的更改。 If I remove this.getSomeData() from the end of this code, I will not get data if the component is initiated without default call on subscription. 如果我从此代码的末尾删除this.getSomeData() ,则如果在没有默认的订阅调用的情况下启动组件,则不会获取数据。 The problem is I am downloading data twice, and I feel like it's possible to do it once. 问题是我下载了两次数据,并且我觉得可以一次下载。

In your service, you can define companySubject as a ReplaySubject instead of a Subject . 在你的服务,你可以定义companySubject作为ReplaySubject而不是Subject The buffer size can be set to 1, so that it "replays" only the last emitted value. 缓冲区大小可以设置为1,以便仅“重播”最后发出的值。

private companySubject = new ReplaySubject<Company>(1);

A new view will be notified as soon as it subscribes to the observable, if CompanyState has already emitted a value. 如果CompanyState已经发出了值,则新视图将在订阅可观察对象后立即得到通知。 As a consequence, you can remove the direct call to getSomeData() in your component initialization code. 因此,您可以在组件初始化代码中删除对getSomeData()的直接调用。

See this answer for details about the various Subject classes. 有关各种Subject类的详细信息,请参见此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM