亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時(shí)間:2018年07月13日 15:01:25   作者:zhiyu  
這篇文章主要介紹了Angular5.0 子組件通過service傳遞值給父組件的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

一、引言

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

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

二、實(shí)現(xiàn)

1.安裝ngx-loading 詳情點(diǎn)擊

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.新建一個(gè)UtilsService

import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';

@Injectable()
export class UtilsService {

 private loadingSource = new Subject();
 // 獲得一個(gè)Observable;
 loadingObservable = this.loadingSource.asObservable();

 // 發(fā)射數(shù)據(jù),當(dāng)調(diào)用這個(gè)方法的時(shí)候,Subject就會(huì)發(fā)射這個(gè)數(shù)據(jù),所有訂閱了這個(gè)Subject的Subscription都會(huì)接受到結(jié)果
 // loading true為啟用loading,false為關(guān)閉loading
 emitBoolean(loading: boolean) {
  this.loadingSource.next(loading);
 }
}

5.在app.component.ts使用subscribe來訂閱,當(dāng)數(shù)據(jù)被發(fā)射出來的時(shí)候,這里就會(huì)接收到結(jié)果

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來訂閱,當(dāng)數(shù)據(jù)被發(fā)射出來的時(shí)候,這里就會(huì)接收到結(jié)果
  this.subscription = this.utils.loadingObservable.subscribe(loading => this.loading = Boolean(loading));
 }

 ngOnInit() {
 }

 /* 銷毀的時(shí)候需要取消訂閱,因?yàn)橛嗛喼髸?huì)一直處于觀察者狀態(tài),不取消會(huì)導(dǎo)致泄露*/
 ngOnDestroy() {
  this.subscription.unsubscribe();
 }

}

6.在其他子組件需要啟用或關(guān)閉loading時(shí),只需要一行代碼。

constructor( private utils: UtilsService) {

       }
this.utils.emitBoolean(true); // 啟用loading
this.utils.emitBoolean(false); // 關(guān)閉loading

7.額外方法:在子組件注入AppComponent,簡單粗暴,但不推薦……

 constructor(public appComponent: AppComponent) {
  
 }
this.appComponent.loading = true; // 啟用loading
this.appComponent.loading = false; // 關(guān)閉loading

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

相關(guān)文章

最新評(píng)論