Angular 7中,可以使用单例服务在两个组件之间进行通信。下面是一个示例解决方法:
CommunicationService
,并在app.module.ts
文件中将其提供为全局的单例服务。import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CommunicationService {
private messageSource = new Subject();
message$ = this.messageSource.asObservable();
sendMessage(message: string) {
this.messageSource.next(message);
}
}
CommunicationService
注入并调用sendMessage
方法发送消息。import { Component } from '@angular/core';
import { CommunicationService } from './communication.service';
@Component({
selector: 'app-sender',
template: `
`
})
export class SenderComponent {
constructor(private communicationService: CommunicationService) {}
sendMessage() {
this.communicationService.sendMessage('Hello from SenderComponent!');
}
}
CommunicationService
注入并订阅message$
监听消息。import { Component, OnDestroy } from '@angular/core';
import { CommunicationService } from './communication.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-receiver',
template: `
{{ message }}
`
})
export class ReceiverComponent implements OnDestroy {
message: string;
subscription: Subscription;
constructor(private communicationService: CommunicationService) {
this.subscription = this.communicationService.message$.subscribe(message => {
this.message = message;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
SenderComponent
和ReceiverComponent
添加到模板中。
这样,当点击“发送消息”按钮时,SenderComponent
会调用CommunicationService
的sendMessage
方法发送消息,然后ReceiverComponent
会监听到该消息并将其展示在页面上。