欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Angular父子组件通过服务传参的示例方法

程序员文章站 2022-07-22 11:58:31
今天在使用ngx-translate做多语言的时候遇到了一个问题,需要在登录页面点击按钮,然后调用父组件中的一个方法。 一开始想到了@input和@output,然而由于...

今天在使用ngx-translate做多语言的时候遇到了一个问题,需要在登录页面点击按钮,然后调用父组件中的一个方法。
一开始想到了@input和@output,然而由于并不是单纯的父子组件关系,而是包含路由的父子组件关系,所以并不能使用@input方法和@output方法。

然后去搜索一下,发现*上有答案,用的是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);
 }
}

然后把这个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);
 });
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。