国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Angular父子組件通過服務(wù)傳參的示例方法

2024-05-06 15:28:18
字體:
供稿:網(wǎng)友

今天在使用ngx-translate做多語言的時候遇到了一個問題,需要在登錄頁面點(diǎn)擊按鈕,然后調(diào)用父組件中的一個方法。
一開始想到了@input和@output,然而由于并不是單純的父子組件關(guān)系,而是包含路由的父子組件關(guān)系,所以并不能使用@input方法和@output方法。

然后去搜索一下,發(fā)現(xiàn)stackoverflow上有答案,用的是service來進(jìn)行傳參,發(fā)現(xiàn)很好用,所以和大家分享一下。

首先,創(chuàng)建一個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方法傳遞參數(shù):

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'); }}

父組件通過服務(wù)接收參數(shù):

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); }); }}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯新站長站。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 湛江市| 顺平县| 阿坝| 镇巴县| 全椒县| 左云县| 茂名市| 阳山县| 卢湾区| 佛教| 南华县| 盐边县| 札达县| 随州市| 马关县| 长治市| 芦溪县| 阳山县| 六枝特区| 海口市| 三江| 江西省| 汉阴县| 哈尔滨市| 社旗县| 沈丘县| 忻州市| 桑日县| 浦东新区| 漳浦县| 香河县| 贺兰县| 双峰县| 隆子县| 青田县| 鄂托克前旗| 清丰县| 靖江市| 武宣县| 永春县| 镇雄县|