繁体   English   中英

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

[英]Data sharing between components in Angular 6

我创建了2个组件和一个服务,如下所示,

组件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);
    });
  }
}

我目前面临的问题是

在页加载两种组分订户被触发,但是当我使用sendTestDataFirstComponent()方法将数据推,仅在FirstComponent订户被触发。 SecondComponent中的订户未被触发。 我应该怎样做才能让两个订阅者使用sendTestData()方法推送数据?

我的控制台日志如下。

收到1 - 测试

收到2 - 测试

收到1 - 从1发送数据

预期产出..

收到1 - 测试

收到2 - 测试

收到1 - 从1发送数据

收到2 - 从1发送数据

这是因为您在AppComponentOneAppComponentTwo提供了两次相同的服务,因此它们都具有相同服务的不同实例。

两个组件的空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 { }

对我来说很好。 检查这个演示控制台

这是相关的代码

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);
    })
 }


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

在将新数据设置为行为主题后,您必须调用observable。

暂无
暂无

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

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