最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Angular父子组件通过服务传参的示例方法
时间:2022-06-25 15:30:52 编辑:袖梨 来源:一聚教程网
今天在使用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();
// Observable string streams
changeEmitted$ = this.emitChangeSource.asObservable();
// Service message commands
emitChange(change: any) {
this.emitChangeSource.next(change);
}
}
然后把这个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);
});
}
}
相关文章
- 铁路12306官网登录入口-铁路12306官网登录失败怎么办 02-17
- 啵乐腐味2026最新版-啵乐官方漫画网页版极速下载 02-17
- 樱花动漫app下载安卓最新版本-樱花动漫app免费版官方下载入口 02-17
- 免费追漫画神器-更新超快的漫画大全 02-17
- 懒猫漫画app下载入口安卓苹果通用 - 懒猫漫画app最新版本官方正版安装包一键获取 02-17
- 美团外卖膨胀券领取入口-在哪快速领券 02-17