当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > Angular5.0 子组件通过service传递值给父组件的方法

Angular5.0 子组件通过service传递值给父组件的方法

2018年08月06日  | 移动技术网IT编程  | 我要评论
一、引言 我们使用ngx-loading,需要在app.component.html上写模板,绑定一个布尔值loading.此时如果我们想在其他组件中使用这个load

一、引言

我们使用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); // 启用loading
this.utils.emitboolean(false); // 关闭loading

7.额外方法:在子组件注入appcomponent,简单粗暴,但不推荐……

 constructor(public appcomponent: appcomponent) {
  
 }
this.appcomponent.loading = true; // 启用loading
this.appcomponent.loading = false; // 关闭loading

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网