简体   繁体   English

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

[英]Data sharing between components in Angular 6

I have created 2 components and one service as below, 我创建了2个组件和一个服务,如下所示,

component-interaction.service.ts 组件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 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 second.component.ts

export class SecondComponent {

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

The issue I am currently facing is 我目前面临的问题是

On page load both the components subscribers are being triggered, but when I push data using sendTestData() method in FirstComponent , only the subscriber in FirstComponent is being triggered. 在页加载两种组分订户被触发,但是当我使用sendTestDataFirstComponent()方法将数据推,仅在FirstComponent订户被触发。 The subscriber in SecondComponent is not being triggered. SecondComponent中的订户未被触发。 What should I do for both subscribers to get triggered on pushing data using the sendTestData() method? 我应该怎样做才能让两个订阅者使用sendTestData()方法推送数据?

My Console logs are as below.. 我的控制台日志如下。

Received at 1 -- Test 收到1 - 测试

Received at 2 -- Test 收到2 - 测试

Received at 1 -- sending data from 1 收到1 - 从1发送数据

Expected Output.. 预期产出..

Received at 1 -- Test 收到1 - 测试

Received at 2 -- Test 收到2 - 测试

Received at 1 -- sending data from 1 收到1 - 从1发送数据

Received at 2 -- sending data from 1 收到2 - 从1发送数据

It is because you provide the same service twice in both AppComponentOne and AppComponentTwo so they both have different instances of the same service. 这是因为您在AppComponentOneAppComponentTwo提供了两次相同的服务,因此它们都具有相同服务的不同实例。

Empty providers array of both component and provide the service within app.module.ts 两个组件的空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
})

app.module.ts

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent, 
  FirstComponent, SecondComponent
  ],
  bootstrap:    [ AppComponent ],
  providers: [ComponentService] // <= provide it here
})
export class AppModule { }

working fine for me. 对我来说很好。 check this demo console 检查这个演示控制台

and here is the relevant code 这是相关的代码

common.service.ts 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 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 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);
    })
 }


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

You must call the observable after setting new data to the behavior subject. 在将新数据设置为行为主题后,您必须调用observable。

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

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