如何在其他视图中向其他组件发送消息

时间:2019-01-11 21:12:38

标签: javascript angular typescript

我有两个具有不同视图的不同组件。第一个组件是带有按钮的仪表板。第二部分是餐厅的部分。单击仪表盘视图中的“接受”按钮时,如何更改将在餐厅视图中显示的文本的值?

例如,餐厅视图中的消息窗口显示消息“等待来自餐厅的消息”。在餐厅视图中,单击“接受”,然后在餐厅视图中将烟囱更改为“预订接受”

这是我的服务

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';


@Injectable({
providedIn: 'root'
})
export class CommunicateService {

private message = new BehaviorSubject('Wait for a message from the restaurant');
currentMessage = this.message.asObservable();

constructor () {}

changeMessage(message: string) {
this.message.next(message);
  }
}

这是我的dashboard.component.ts

import {CommunicateService } from '../../services/communicate.service';
import { Component, OnInit } from '@angular/core';

export class DashboardComponent {
message: string;


constructor(private cs: CommunicateService) implements OnInit {}

ngOnInit() {
this.cs.currentMessage.subscribe(message => this.message = message);
}

newMessage() {
this.cs.changeMessage('Reservation accept!');
}
}

dasboard.component.html

<button (click)="newMessage()">Accept</button>

restaurant.component.ts

import { Component, OnInit } from '@angular/core';
import { CommunicateService } from '../../../services/communicate.service';

export class RestaurantComponent implements OnInit {

 message: string;


 constructor(private cs: CommunicateService) {}

 ngOnInit() {
 this.cs.currentMessage.subscribe(message => this.message = message);
 }
}

and restaurant.component.html

<div *ngIf="message" class="alert alert-success">{{message}}</div>

0 个答案:

没有答案