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

Communication between 2 components through service doesn't working

我需要这方面的帮助。我想通过共享服务将变量从组件发送到另一个组件。我受到 的启发,但在接收器组件中 "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
                }
}

试试这个.. 改变

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

试试这个代码

服务:

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