国产探花免费观看_亚洲丰满少妇自慰呻吟_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            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 房产| 托克逊县| 福泉市| 德化县| 邳州市| 韶关市| 古丈县| 锦屏县| 平山县| 永春县| 大港区| 定安县| 灵石县| 华蓥市| 天台县| 德钦县| 大洼县| 崇仁县| 剑川县| 泽库县| 木兰县| 思茅市| 台东县| 抚顺县| 太原市| 乌拉特后旗| 阿图什市| 太湖县| 营口市| 洛扎县| 望江县| 沾益县| 遂昌县| 班戈县| 南通市| 汽车| 当雄县| 云浮市| 南城县| 西丰县| 商南县|