如何通过服务在组件之间发送消息

时间:2019-11-04 17:44:27

标签: angular

我有两个组成部分:ping和pong,Ping应该通过服务向pong发送消息。通过使用Rxjs,尽管我正在使用官方文档示例,但我似乎没有发送或接收任何内容。 这是服务和两个组件的代码:

服务文件:

import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MessagingServiceService {
  private _message : Subject<string>  = new Subject<string>();
  message$ : Observable<string>;
  constructor() { 
    this.message$ = this._message.asObservable();
  }

  sendMessage(message: string)
  {
    console.log(this.message$);
    this._message.next(message);
  }
}

Ping组件:

import { Component, OnInit } from '@angular/core';
import { MessagingServiceService } from '../messaging-service.service';

@Component({
  selector: 'app-ping',
  templateUrl: './ping.component.html',
  styleUrls: ['./ping.component.css']
})
export class PingComponent implements OnInit {

  message :string = "";
  constructor(private messageService : MessagingServiceService) { }

  ngOnInit() {
  }

  sendMessage()
  {
    console.log(this.message);
    this.messageService.sendMessage(this.message);
  }

}

乒乓组件:

import { Component, OnInit } from '@angular/core';
import { MessagingServiceService } from '../messaging-service.service';


@Component({
  selector: 'app-pong',
  templateUrl: './pong.component.html',
  styleUrls: ['./pong.component.css']
})
export class PongComponent implements OnInit {

  recivedMessage :string ="";
  constructor(private messagingService: MessagingServiceService) {
    this.reciveMessages();
    this.messagingService.message$.subscribe(res=>{
      console.log(res);
      this.recivedMessage = res;
    })

   }

  ngOnInit() {
  }

  reciveMessages()
  {
    this.messagingService.message$.subscribe(res=>{
      console.log(res);
      this.recivedMessage = res;
    })
  }

}

1 个答案:

答案 0 :(得分:0)

按如下所示更改服务。

import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MessagingServiceService {
  private _message : Subject<string>  = new Subject<string>();

  constructor() { 
  }

  sendMessage(message: string)
  {
    this._message.next(message);
  }

  getMessage(): Observable<any> {
    return this._message.asObservable();
  }
}

请按如下所示更改您的subsribe方法。

import { Component, OnInit,OnDestroy } from '@angular/core';
import { MessagingServiceService } from '../messaging-service.service';


@Component({
  selector: 'app-pong',
  templateUrl: './pong.component.html',
  styleUrls: ['./pong.component.css']
})
export class PongComponent implements OnInit, OnDestroy {

  subscription: Subscription;

  recivedMessage :string ="";

  constructor(private messagingService: MessagingServiceService) {

   this.subscription = this.messagingService.getMessage().subscribe(res => {
      this.recivedMessage = res;
   });

  }

  ngOnInit() {
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }