在这种情况下,要使用服务将消息从一个组件传递到另一个组件,您可以创建全局消息总线或事件总线 (publish/subscribe pattern)。
为此,我们需要来自Rxjs 的Subject(使用.next() 方法发出值)和Observable(使用.subscribe() 收听消息),这现在是角度6 的重要组成部分。 (对于这个例子,我使用 Rxjs 6 和 rxjs-compat 包)
在这里,我们将使用MessageService 类发送消息,该类声明为@Injectable,以作为组件中的依赖项注入。该消息将在来自 app.component.html 的按钮单击时发出。将在message.component.ts 中检索相同的消息,以在 html 模板message.component.html 中显示它。我们将在app.component.html 中包含MessageComponent 的选择器<app-messagecomponent></app-messagecomponent>。
下面是完整的代码
message.service.ts
import { Injectable } from '@angular/core';
import { Observable,Subject} from 'rxjs';
@Injectable()
export class MessageService {
private subject = new Subject<any>();
sendMessage(message: string) {
this.subject.next({ text: message });
}
clearMessage() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
app.component.ts
import { Component } from '@angular/core';
import { MessageService } from './message.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 6';
constructor(private service:MessageService){}
sendMessage(): void {
// send message to subscribers via observable subject
this.service.sendMessage('Message from app Component to message Component!');
}
clearMessage():void{
this.service.clearMessage();
}
}
app.component.html
<button (click)="sendMessage()">Click here to test message</button> <br><br>
<app-messagecomponent></app-messagecomponent>
message.component.ts
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { MessageService } from './message.service';
@Component({
selector: 'app-messagecomponent',
templateUrl: 'message.component.html'
})
export class MessageComponent implements OnDestroy {
message: any = {};
subscription: Subscription;
constructor(private messageService: MessageService) {
// subscribe to app component messages
this.subscription = this.messageService.getMessage().subscribe(message => { this.message = message; });
}
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
}
}
message.component.html
<p>The incoming message : </p> <br>
{{message?.text }}
这里我使用了 Elvis 运算符,以防 message 是 undefined 。
这是一个工作演示:https://stackblitz.com/edit/rxjs-snaghl
如果您正在寻找类似的东西,请告诉我。