在Angular中,可以使用服务来处理在没有关联的组件之间进行带返回值的通信。
首先,在项目中创建一个服务。在创建服务时,需要声明一个名为“Subject”的RxJS可观察对象。此外,还需要创建两个方法:一个用于发送数据,另一个用于接收数据。
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
private data = new Subject
send(data: any) { this.data.next(data); }
getData() { return this.data.asObservable(); } }
在发送数据的组件中(例如,组件A),使用服务发送数据。具体来说,使用send()方法发送数据。
import { Component } from '@angular/core'; import { DataService } from './data.service';
@Component({
selector: 'app-component-a',
template:
})
export class ComponentA {
constructor(private dataService: DataService) {}
sendData() { this.dataService.send({data: 'Hello from Component A'}); } }
在另一个组件(例如,组件B)中,使用服务接收数据。使用getData()方法获取名为“Subject”的可观察对象,并使用subscribe()方法订阅数据。
import { Component, OnDestroy } from '@angular/core'; import { DataService } from './data.service'; import { Subscription } from 'rxjs';
@Component({
selector: 'app-component-b',
template: Received Data: {{receivedData}}
})
export class ComponentB implements OnDestroy {
receivedData: any;
subscription: Subscription;
constructor(private dataService: DataService) { this.subscription = this.dataService.getData().subscribe(data => { this.receivedData = data; }); }
ngOnDestroy() { this.subscription.unsubscribe(); } }
在这个