我正在尝试如何传递来自 app.component.ts
的消息显示在messageComponent.ts
关于 app.component.html
我添加了 <app-messagecomponent></app-messagecomponent>
添加它什么也没显示的那一刻。
我在服务中也有一个方法:
消息.服务.ts
message(message) {
return message;
}
所以我想通过消息服务传递来自其他组件的消息,以便它显示在 app-messagecomponent.html 中
例如来自 app.component.ts:
sendMessageToService() {
this.myservice.message('my Message to be displayed in the messageComponent');
}
我该怎么做?
最佳答案
在这种情况下,要使用服务将消息从一个组件传递到另一个组件,您可以创建全局消息总线或事件总线 (publish/subscribe pattern
)。
为此我们需要 Subject
(使用 .next()
方法发出值)和 Observable
(使用 .subscribe()
收听来自 Rxjs
的消息)现在是 angular 6 的重要组成部分。(对于这个例子,我使用 Rxjs 6 和 rxjs-compat 包)
这里我们将使用 MessageService
发送消息声明为 @Injectable
的类作为组件的依赖项注入(inject)。单击来自 app.component.html
的按钮时将发出消息.将在 message.component.ts
中检索到相同的消息在 html 模板中显示它 message.component.html
.我们将包含 MessageComponent
的选择器这是 <app-messagecomponent></app-messagecomponent>
在app.component.html
.
完整代码如下
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
如果您正在寻找这样的东西,请告诉我。
关于Angular 6 - 通过服务将消息从组件传递到消息组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50371582/