今天在使用 ngx-translate 做多语言的时候遇到了一个问题, 需要在登录页面点击按钮, 然后调用父组件中的一个方法.
一开始想到了 @input 和 @output, 然而由于并不是单纯的父子组件关系, 而是包含路由的父子组件关系, 所以并不能使用 @input 方法和 @output 方法.
然后去搜索一下, 发现 Stack Overflow 上有答案, 用的是 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);
- }
- }//
- 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);
- });
- }
- }
来源: http://www.qdfuns.com/article/51117/f3921369b9fdb64acb0953c3407fd17b.html