一、引言
我們使用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
新聞熱點
疑難解答
圖片精選