在Angular 8中,可以使用服务(service)来在兄弟组件之间发送数据。以下是一个包含代码示例的解决方法:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
private dataSubject = new Subject();
sendData(data: any) {
this.dataSubject.next(data);
}
getData() {
return this.dataSubject.asObservable();
}
}
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-sender',
template: `
`
})
export class SenderComponent {
constructor(private dataService: DataService) {}
send() {
const data = 'Hello, receiver!';
this.dataService.sendData(data);
}
}
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-receiver',
template: `
{{ receivedData }}
`
})
export class ReceiverComponent implements OnInit {
receivedData: any;
constructor(private dataService: DataService) {}
ngOnInit() {
this.dataService.getData().subscribe(data => {
this.receivedData = data;
});
}
}
通过上述方法,SenderComponent可以通过DataService将数据发送给ReceiverComponent,并在ReceiverComponent中订阅数据以接收并显示它们。