通过服务的2个组件之间的通信不起作用

时间:2018-08-08 18:37:31

标签: angular angular-services

我需要帮助。我想通过共享服务将变量从组件发送到另一个组件。我受到this solution的启发,但是在接收器组件中,“ nevim”值仍然不确定,我也不知道为什么。非常感谢。

编辑:好的,我发现了问题,原因是发件人和接收者组件未使用同一服务实例。

因此,如果您在自己的项目中尝试使用此工具,则应该可以使用。

服务:

customNevim$: Observable<string>;
private customNevimSubject = new Subject<string>();

constructor() {
    this.customNevim$ = this.customNevimSubject.asObservable();
}

customNevim(data) {
    this.customNevimSubject.next(data);
}

发件人组件:

 message2: string = "test";

 public constructor( private myService: MyService) {
     this.myService.customNevim(this.message2);
 }

收件人组件:

nevim: string;

public constructor( private myService: MyService) {
    this.myService.customNevim$.subscribe((data) => {
                    this.nevim = data; 
                    //after I try console.log "this.nevim" it still shows it as undefined
                }
}

2 个答案:

答案 0 :(得分:0)

尝试一下。更改

this.customNevim$ = this.customNevimSubject.asObservable();

在构造函数中什么也没有,您的观察值应该是

非rxjs6-> this.customNevim$ = Observable.from(this.customNevimSubject); import "rxjs/add/observable/from";

Rxjs6-> this.customNevim$ = from(this.customNevimSubject);

Rrxjs6->从import { from } from 'rxjs';导入

更新您的示例...

服务

private customNevimSubject = new BehaviourSubject<string>("TestBehaviour");
customNevim$: Observable<string> = Observable.from(this.customNevimSubject);

constructor(){}

customNevim(data) {
  this.customNevimSubject.next(data);
}

发件人组件

 message2: string = "test";

 constructor(private myService: MyService){}

 ngOnInit(){
   this.myService.customNevim(this.message2);
 }

收件人组件

nevim: string;

constructor(private myService: MyService){}

ngOninit(){
       this.myService.customNevim$.subscribe((data) => {
         /// Log the data
         console.log(data);
       }
}

答案 1 :(得分:0)

尝试此代码

服务:

customNevim$: Observable<string>;
private customNevimSubject = new Subject<string>();

constructor() {
    this.customNevim$ = this.customNevimSubject.asObservable();
}

customNevim(data) {
    this.customNevimSubject.next(data);
}

发件人组件:

message2: string = "test";

 public constructor( private myService: MyService) {

 }

 ngOnInit() {
   this.myService.customNevim(this.message2);
}

收件人组件:

nevim: string;

public constructor( private myService: MyService) {

}

ngOnInit() {
    this.myService.customNevim$.subscribe((data) => {
         this.nevim = data; 
    });
}