在Angular中,组件之间的通信可以使用@Input,@Output和SharedService来实现。这三种方法各有其优势,具体使用哪个取决于场景和需求。
下面是一个使用@Input和@Output的示例:
// 子组件
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'child-component',
template: `
`
})
export class ChildComponent {
@Input() data: string;
@Output() sendDataToParent: EventEmitter = new EventEmitter();
sendData() {
this.sendDataToParent.emit(this.data);
}
}
// 父组件
import { Component } from '@angular/core';
@Component({
selector: 'parent-component',
template: `
`
})
export class ParentComponent {
parentData = 'Hello from parent';
receiveData(data: string) {
console.log(data);
}
}
下面是一个使用SharedService的示例:
// SharedService
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable()
export class DataService {
private dataSubject = new Subject();
data$ = this.dataSubject.asObservable();
sendData(data: string) {
this.dataSubject.next(data);
}
}
// 子组件
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'child-component',
template: `
`
})
export class ChildComponent {
constructor(private dataService: DataService) {}
sendData() {
this.dataService.sendData('Hello from child');
}
}
// 父组件
import { Component, OnDestroy } from '@angular/core';
import { DataService } from './data.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'parent-component',
template: `
`
})
export class ParentComponent implements OnDestroy {
private dataSubscription: Subscription;
constructor(private dataService: DataService) {
this.dataSubscription = this.dataService.data$.subscribe(data => {
console.log(data);
});
}
ngOnDestroy() {
this.dataSubscription.unsubscribe();
}
}
在这个示例中,子组件通过调用DataService的sendData方法发送数据,父组件通过订阅DataService的data$可观察对象来接收数据。
上一篇:Angular组件之间的通信