在Angular中,有多种方式可以实现组件之间的消息传递,例如:
parent.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'parent-component',
template: `
Received Message: {{message}}
`
})
export class ParentComponent {
message: string;
receiveMessage($event) {
this.message = $event;
}
}
child.component.ts:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'child-component',
template: `
`,
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter();
sendMessage() {
this.messageEvent.emit('Hello World!');
}
}
message.service.ts:
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class MessageService {
private messageSource = new BehaviorSubject
changeMessage(message: string) { this.messageSource.next(message); } }
parent.component.ts:
import { Component } from '@angular/core'; import { MessageService } from './message.service';
@Component({
selector: 'parent-component',
template: {{message}}
})
export class ParentComponent {
message: string;
constructor(private messageService: MessageService) { this.messageService.currentMessage.subscribe(message => this.message = message) } }
child.component.ts:
import { Component } from '@angular/core'; import { MessageService } from './message.service';
@Component({
selector: 'child-component',
template:
,
})
export class ChildComponent {
constructor(private messageService: MessageService) {}
sendMessage() { this.messageService.changeMessage('Hello World!'); }
上一篇:Angular组件之间的通信:使用@Input,@Output和SharedService。应该使用哪个?
下一篇:Angular组件之间的状态管理(直接依赖)返回NullInjectorError - R3InjectorError