Angular父子组件通过服务传参
投稿于 被查看 40980 次 评论:209
Angular父子组件通过服务传参
今天在使用ngx-translate做多语言的时候遇到了一个问题,需要在登录页面点击按钮,然后调用父组件中的一个方法。
一开始想到了@input和@output,然而由于并不是单纯的父子组件关系,而是包含路由的父子组件关系,所以并不能使用@input方法和@output方法。
然后去搜索一下,发现stackoverflow上有答案,用的是service来进行传参,发现很好用,所以和大家分享一下。
首先,创建一个service.
shared-service.ts import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; @Injectable() export class SharedService { // Observable string sources private emitChangeSource = new Subject<any>(); // Observable string streams changeEmitted$ = this.emitChangeSource.asObservable(); // Service message commands emitChange(change: any) { this.emitChangeSource.next(change); } }// 欢迎加入全栈开发交流群一起学习交流:864305860
然后把这个service分别注入父组件和子组件所属的module中,记得要放在providers里面。
然后把service再引入到父子组件各自的component里面。
子组件通过onClick方法传递参数:
child.component.ts import { Component} from '@angular/core'; @Component({ templateUrl: 'child.html', styleUrls: ['child.scss'] }) export class ChildComponent { constructor( private _sharedService: SharedService ) { } onClick(){ this._sharedService.emitChange('Data from child'); } }
父组件通过服务接收参数:
parent.component.ts import { Component} from '@angular/core'; @Component({ templateUrl: 'parent.html', styleUrls: ['parent.scss'] }) export class ParentComponent { constructor( private _sharedService: SharedService ) { _sharedService.changeEmitted$.subscribe( text => { console.log(text); }); } }
本次给大家推荐一个免费的学习群,里面概括移动应用网站开发,css,html,webpack,vue node angular以及面试资源等。
对web开发技术感兴趣的同学,欢迎加入Q群:864305860,不管你是小白还是大牛我都欢迎,还有大牛整理的一套高效率学习路线和教程与您免费分享,同时每天更新视频资料。
最后,祝大家早日学有所成,拿到满意offer,快速升职加薪,走上人生巅峰。
用户评论