在Angular 6中使用Observable在兄弟组件之间触发事件的解决方法可以分为以下几个步骤:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable()
export class SharedService {
private subject = new Subject();
sendMessage(message: string) {
this.subject.next({ text: message });
}
clearMessages() {
this.subject.next();
}
getMessage() {
return this.subject.asObservable();
}
}
import { Component, OnInit } from '@angular/core';
import { SharedService } from './shared.service';
@Component({
selector: 'app-sender',
template: `
`,
})
export class SenderComponent {
constructor(private sharedService: SharedService) { }
sendMessage() {
this.sharedService.sendMessage('Hello from sender component!');
}
}
import { Component, OnInit } from '@angular/core';
import { SharedService } from './shared.service';
@Component({
selector: 'app-receiver',
template: `
{{ message }}
`,
})
export class ReceiverComponent implements OnInit {
message: string;
constructor(private sharedService: SharedService) { }
ngOnInit() {
this.sharedService.getMessage().subscribe(message => {
this.message = message.text;
});
}
}
通过以上步骤,你可以在兄弟组件之间通过共享服务和Observable来触发事件和共享数据。当发送组件中的按钮被点击时,会发送一条消息到接收组件,并在接收组件中显示出来。