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

首頁 > 語言 > JavaScript > 正文

Angular5.0 子組件通過service傳遞值給父組件的方法

2024-05-06 15:32:43
字體:
來源:轉載
供稿:網友

一、引言

我們使用ngx-loading,需要在app.component.html上寫模板,綁定一個布爾值loading.此時如果我們想在其他組件中使用這個loading控件,就需要在每個組件的html重新寫模板,這就顯得累贅了。在此,我們以ngx-loading為例,展示子組件如何通過service改變app組件中的布爾值loading。

// app.component.html <ngx-loading [show]="loading" [config]="{ backdropBorderRadius: '14px' }"></ngx-loading>

二、實現

1.安裝ngx-loading 詳情點擊

npm install --save ngx-loading

2.Import the LoadingModule

import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { CoreModule } from './core/core.module';import { LoadingModule } from 'ngx-loading';@NgModule({ //... imports: [  //...  LoadingModule ], //...})export class AppModule { }

3.在app.component.html寫ngx-loading模板

// app.component.html <ngx-loading [show]="loading" [config]="{ backdropBorderRadius: '14px' }"></ngx-loading>

4.新建一個UtilsService

import {Injectable} from '@angular/core';import {Subject} from 'rxjs/Subject';@Injectable()export class UtilsService { private loadingSource = new Subject(); // 獲得一個Observable; loadingObservable = this.loadingSource.asObservable(); // 發射數據,當調用這個方法的時候,Subject就會發射這個數據,所有訂閱了這個Subject的Subscription都會接受到結果 // loading true為啟用loading,false為關閉loading emitBoolean(loading: boolean) {  this.loadingSource.next(loading); }}

5.在app.component.ts使用subscribe來訂閱,當數據被發射出來的時候,這里就會接收到結果

import {Component, OnDestroy, OnInit} from '@angular/core';import {Subscription} from "rxjs/Subscription";import {UtilsService} from "./service/utils.service";@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent implements OnInit, OnDestroy { loading = false; subscription: Subscription; constructor(public utils: UtilsService) {  // 使用subscribe來訂閱,當數據被發射出來的時候,這里就會接收到結果  this.subscription = this.utils.loadingObservable.subscribe(loading => this.loading = Boolean(loading)); } ngOnInit() { } /* 銷毀的時候需要取消訂閱,因為訂閱之后會一直處于觀察者狀態,不取消會導致泄露*/ ngOnDestroy() {  this.subscription.unsubscribe(); }}

6.在其他子組件需要啟用或關閉loading時,只需要一行代碼。

constructor( private utils: UtilsService) {       }this.utils.emitBoolean(true); // 啟用loadingthis.utils.emitBoolean(false); // 關閉loading            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 临泽县| 平和县| 务川| 且末县| 丁青县| 海南省| 广东省| 海兴县| 巫山县| 东兰县| 舟山市| 剑川县| 勃利县| 汉中市| 灌云县| 沛县| 忻州市| 南开区| 吕梁市| 阳信县| 靖江市| 交城县| 曲麻莱县| 张家港市| 香格里拉县| 资讯 | 鄂托克前旗| 商丘市| 滦平县| 措美县| 普陀区| 抚宁县| 济宁市| 中江县| 额敏县| 綦江县| 东阳市| 新巴尔虎右旗| 海宁市| 曲松县| 佛教|