国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表

圖片精選

主站蜘蛛池模板: 周口市| 武平县| 罗源县| 平舆县| 安化县| 新巴尔虎左旗| 秦皇岛市| 平利县| 应用必备| 曲水县| 安丘市| 镇江市| 信丰县| 蓝山县| 建昌县| 札达县| 富源县| 富阳市| 辽阳县| 双流县| 常德市| 普兰店市| 桃园县| 运城市| 绥中县| 涞源县| 即墨市| 马山县| 德昌县| 芜湖市| 天峨县| 永胜县| 永靖县| 富蕴县| 攀枝花市| 海丰县| 额济纳旗| 临高县| 林周县| 克东县| 平潭县|