我正在开发一个将消息发送到另一个组件的服务。
以下是该服务的代码:
private subject = new Subject<any>();
sendMessage(message: string) {
this.subject.next({ text: message });
}
clearMessage() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
我想要做的是在消息之外添加另一个字符串,以便我可以随身携带它。像这样:
sendMessage(message: string, anotherstring: string) {
this.subject.next({ text: message, anotherstring }); // This does not work
}
我想添加更多这样的参数:
this.service.sendMessage('Message from app Component to message Component!', 'somethingElse');
如何使用消息文本传递更多字符串/参数?
以下是完整代码:
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();
}
}