zoukankan      html  css  js  c++  java
  • Angular通过订阅观察者对象实现不同组件中数据的实时传递

    在angular官方定义中,组件直接的数据交换只要在父子直接传递,但是我们在项目中经常需要在各种层级之间传递数据,下面介绍关于订阅可观察对象实现的数据传递。

    首先定义一个服务app.sevice.ts,服务里面new一个SubJect对象:

    // app.servie.ts
    import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; @Injectable() export class AppService { constructor() { } sub = new Subject<any>(); }

    然后,定义两个组件oneChild和twoChild在app.compnent显示:

    // app.component.ts
    <one-child></one-child>
    <two-child></two-child>

    其中,onChild里面有一个输入框,绑定keyup方法sendText:

    // one-child.component.html
    <p>
      one-child works! <input #input type="text" (keyup)="sendText(input.value)" >
    </p>

    在onChid里面注入app.service,调用sub对象:

    import { Component } from '@angular/core';
    import { AppService } from '../app.service'
    
    @Component({
      selector: 'one-child',
      templateUrl: './one-child.component.html',
      styleUrls: ['./one-child.component.scss']
    })
    export class OneChildComponent {
    
      constructor(
        private appService: AppService
      ) { }
    
      changeText(value) {
        console.log("one-child:" + value);
        this.appService.sub.next(value);
      }
    
    }

    此时,在twoChild里面订阅sub对象获取数据:

    // two-child.component.ts
    import { Component, OnInit } from '@angular/core';
    import { AppService } from '../app.service'
     
    @Component({
      selector: 'two-child',
      templateUrl: './two-child.component.html',
      styleUrls: ['./two-child.component.scss']
    })
    export class TwoChildComponent implements OnInit {
     
      constructor(
        private appService: AppService
      ) { }
     
      ngOnInit() {
        this.appService.sub.subscribe(res => {
          console.log("two-child" + res);
        })
      }
    }

    最终我们就可以看到在oneChild里面输入的数据在twoChild也可以接收到了:

    最后的话,对于订阅对象,在组件销毁的时候,根据实际情况要取消订阅:

    ngOnDestroy() {
      this.appService.sub.unsubscribe();
    }
  • 相关阅读:
    Python之函数进阶
    Python之函数初识
    Python之 文件操作
    数据类型补充
    Python 基础三
    寒假学习第五天
    寒假学习第四天
    寒假学习第三天
    寒假学习第二天
    寒假学习第一天
  • 原文地址:https://www.cnblogs.com/liudongpei/p/8006688.html
Copyright © 2011-2022 走看看