如果组件不是父级的父级或父级的子级,则如何通过服务或任何其他方式将值从一个组件传递到另一个组件?
答案 0 :(得分:-1)
您可以使用service
将数据从组件传递到另一个组件。
data.service.ts
:
@Injectable()
export class DataService {
private data: string;
constructor() {
this.data = 'myData'
}
getData(): Promise<string> {
return Promise.resolve(this.data);
}
setData(data: string) {
this.data = data;
}
}
component A
:
export class ComponentA {
private data: string;
constructor(private dataService: dataService) {
this.getData();
}
getData() {
this.dataService.getData().subscribe(
(data) => {
this.data = data;
}
)
}
setData(data: string) {
this.dataService.setData(data);
}
}
component B
:
export class ComponentB {
private data: string;
constructor(private dataService: dataService) {
this.getData();
}
getData() {
this.dataService.getData().subscribe(
(data) => {
this.data = data;
}
)
}
setData(data: string) {
this.dataService.setData(data);
}
}