角中的父子组件怎么通过服务传参?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
首先,创建一个服务。
共享服务。ts
import {, Injectable },得到& # 39;@angular/核心# 39;; {},Subject  import 得到& # 39;rxjs/话题# 39;; @Injectable () export class  SharedService { ,//Observable string 来源 ,private emitChangeSource =, new Subject(); ,//Observable string 流 ,changeEmitted $=, this.emitChangeSource.asObservable (); ,//Service message 命令 ,emitChange(改变:有),{ ,this.emitChangeSource.next(改变); ,} }
然后把这个服务分别注入父组件和子组件所属的模块中,记得要放在提供者里面。
然后把服务再引入到父子组件各自的组件里面。
子组件通过onClick方法传递参数:
child.component.ts
import {},组件,得到& # 39;@angular/核心# 39;; @ component ({ ,templateUrl: & # 39; child.html& # 39; ,styleUrls: [& # 39; child.scss& # 39;】 }) export class  ChildComponent { ,构造函数( ,private _sharedService: SharedService ,){,} onClick () { ,this._sharedService.emitChange (& # 39; Data 得到孩子# 39;); ,} }
父组件通过服务接收参数:
parent.component.ts
import {},组件,得到& # 39;@angular/核心# 39;; @ component ({ ,templateUrl: & # 39; parent.html& # 39; ,styleUrls: [& # 39; parent.scss& # 39;】 }) export class  ParentComponent { ,构造函数( ,private _sharedService: SharedService ,){ ,_sharedService.changeEmitted .subscribe美元(=,text 祝辞,{ ,console.log(文本); ,}); ,} }
关于角中的父子组件怎么通过服务传参问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。