Angular 6中组件之间的数据共享

时间:2018-11-27 06:13:32

标签: angular observable angular6 behaviorsubject

我已经创建了以下两个组件和一项服务,

component-interaction.service.ts

@Injectable()
export class ComponentInteractionService {

  public dataSubject = new BehaviorSubject<string>("Test");

  getTestData(): Observable<any> {
    return this.dataSubject.asObservable();
  }

  pustTestData(dataToPush: string): void {
    this.dataSubject.next(dataToPush);
  }
}

first.component.ts

export class FirstComponent {

  constructor(private componentInteractionService: ComponentInteractionService) { 
    componentInteractionService.getTestData().subscribe(data=> {
      console.log("Received at 1 -- " + data);
    });
  }

  sendTestData(): void {
    this.componentInteractionService.pustTestData("sending data from 1");
  }

}

second.component.ts

export class SecondComponent {

  constructor(private componentInteractionService: ComponentInteractionService) { 
    componentInteractionService.getTestData().subscribe(data=> {
      console.log("Received at 2 -- " + data);
    });
  }
}

我当前面临的问题是

在页面加载时,两个组件订阅者都被触发,但是当我在 FirstComponent 中使用 sendTestData()方法推送数据时,只有 FirstComponent < / strong>正在被触发。 SecondComponent 中的订阅者未被触发。 对于使用 sendTestData()方法推送数据的两个订阅者,我应该怎么做?

我的控制台日志如下。

在1-测试收到

2点收到-测试

在1接收-从1发送数据

预期输出。

在1-测试收到

2点收到-测试

在1接收-从1发送数据

在2接收-从1发送数据

3 个答案:

答案 0 :(得分:1)

这是因为您在from pandas.tseries.offsets import BDay df['Start_Date'] = pd.to_datetime(df['Start_Date']) df['End_Date'] = df.apply(lambda x: x['Start_Date'] + BDay(x['Days']), axis=1) Days Start_Date End_Date 0 3 2018-08-23 2018-08-28 1 1 2018-08-16 2018-08-17 2 3 2018-08-24 2018-08-29 3 0 2018-08-29 2018-08-29 中两次提供相同的服务,因此它们都具有相同服务的不同实例。

同时包含两个组件的空AppComponentOne数组,并在AppComponentTwo内提供服务

providers

app.module.ts

@Component({
  selector: 'app-distinct-first-component',
  template: '<button (click)="sendTestData()">Click to send Data</button>',
  providers: [ComponentService] // <= remove this line from both components
})

答案 1 :(得分:0)

对我来说很好。检查此demo控制台

这是相关代码

common.service.ts

@Injectable()
export class CommonService {

public dataSubject$: Subject<string> = new BehaviorSubject<string>("Test");

getData(): Observable<any> {
    return this.dataSubject$.asObservable();
}

setData(dataToPush: string): void{
    this.dataSubject$.next(dataToPush);
 }
}

first.component.ts

@Component({
    selector: 'app-first',
    template: `First Component data`,
})

export class FirstComponent implements OnInit {

constructor(
      private commonService: CommonService,
    ) { 

    }

    ngOnInit(){
      this.sendCommonData();
      this.getCommonData();
    }

 getCommonData () {
   this.commonService.getData().subscribe(data=> {
        console.log("Received at 1 -- " + data);
    })
 }

sendCommonData() {
    this.commonService.setData("sending data from first");
}

}

second.component.ts

import { Component, OnInit } from '@angular/core';

import { CommonService } from './common.service';

@Component({
    selector: 'app-second',
    template: `Second Component data `,
})

export class SecondComponent implements OnInit {

constructor(
      private commonService: CommonService,
    ) { 

    }

    ngOnInit(){
      this.getCommonData();
    }

 getCommonData () {
   this.commonService.getData().subscribe(data=> {
        console.log("Received at 2 -- " + data);
    })
 }


}

答案 2 :(得分:0)

 sendTestData(): void {
  this.componentInteractionService.pustTestData("sending data from 1");
  // must call the observable once after adding new data
  this.commonService.getData();
 }

为行为主体设置新数据后,必须调用可观察对象。