Angular:无法将一个子组件的输出传递给另一个子组件
创始人
2024-11-02 02:00:41
0

一个解决方法是通过使用一个中介服务来传递数据。在中介服务中创建一个可观察对象,通过使用该对象来传递数据。给需要访问数据的组件订阅这个可观察对象,每次该对象发生更改时就会触发这些组件。

下面是一个使用中介服务来传递数据的示例:

在first-child.component.ts中,创建一个输出事件:

@Output() public employeeData = new EventEmitter();

在first-child.component.html中,触发输出事件:

onClick() { let employee = { id: 1, name: 'John Doe' }; this.employeeData.emit(employee); }

创建一个名为MediatorService的服务:

import { Injectable } from '@angular/core'; import { Observable, Subject } from 'rxjs';

@Injectable({ providedIn: 'root' }) export class MediatorService { private employeeData$: Subject = new Subject();

public sendEmployeeData(employee: any) { this.employeeData$.next(employee); }

public getEmployeeData(): Observable { return this.employeeData$.asObservable(); }

}

在first-child.component.ts中,注入中介服务并触发事件:

import { MediatorService } from './mediator.service'; @Component({ selector: 'app-first-child', template: }) export class FirstChildComponent { constructor(private mediatorService: MediatorService) {}

onClick() { let employee = { id: 1, name: 'John Doe' }; this.mediatorService.sendEmployeeData(employee); }

}

在second-child.component.ts中,订阅中介服务并获取相应的数据:

import { MediatorService } from './mediator.service';

@Component({ selector: 'app-second-child', template: ``, styleUrls: ['./second-child.component.css'] }) export class SecondChildComponent implements OnInit {

constructor(private mediatorService: MediatorService) {}

ngOnInit(): void { this.mediatorService.getEmployeeData().subscribe((employee) => { console.log('Received employee data:', employee); }); }

}

这样,第二个子组件就可以从第一个子组件中获取数据,并且不用直接传递数据。

相关内容

热门资讯

透视免费"雀友会免费... 透视免费"雀友会免费自动挂机脚本"总是存在有辅助app(哔哩哔哩)1、超多福利:超高返利,海量正版游...
据目击者称"欢乐对决... 据目击者称"欢乐对决脚本辅助器ios"好像真的是有辅助工具(哔哩哔哩)暗藏猫腻,小编详细说明欢乐对决...
透视黑科技"微信决胜... 透视黑科技"微信决胜游戏辅助"原来真的是有辅助攻略(哔哩哔哩)1、微信决胜游戏辅助有没有辅助教程、微...
技巧辅助挂"欢乐对决... 技巧辅助挂"欢乐对决手游辅助"总是存在有辅助方法(哔哩哔哩)1、超多福利:超高返利,海量正版游戏,欢...
据了解"新众乐辅助&... 据了解"新众乐辅助"都是是有辅助脚本(哔哩哔哩)1、新众乐辅助有没有辅助教程、新众乐辅助有透视吗等服...
透视挂透视"福建天天... 透视挂透视"福建天天开心辅助器"好像是有辅助方法(哔哩哔哩)1)福建天天开心辅助器免费钻石:进一步探...
透视玄学"边锋老友怎... 透视玄学"边锋老友怎么开挂"都是是真的有辅助app(哔哩哔哩)1、边锋老友怎么开挂模拟器是什么优化,...
黑科技攻略"大唐山西... 黑科技攻略"大唐山西辅助软件"都是确实有辅助神器(哔哩哔哩)1、很好的工具软件,可以解锁游戏的大唐山...
受玩家影响"微信中至... 受玩家影响"微信中至有辅助吗"果然是真的有辅助软件(哔哩哔哩)1、在微信中至有辅助吗插件功能辅助器技...
事发当天"闲来辅助神... 事发当天"闲来辅助神器下载2022"竟然是有辅助插件(哔哩哔哩)1、闲来辅助神器下载2022免费脚本...