首页 > 解决方案 > 如何通过服务在组件之间发送消息

问题描述

我有这两个组件: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;
    })
  }

}

标签: angular

解决方案


更改服务如下。

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

请更改您的订阅方法,如下所示。

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

推荐阅读