Angular經過訂閱觀察者對象實現不一樣組件中數據的實時傳遞

在angular官方定義中,組件直接的數據交換隻要在父子直接傳遞,可是咱們在項目中常常須要在各類層級之間傳遞數據,下面介紹關於訂閱可觀察對象實現的數據傳遞。css

首先定義一個服務app.sevice.ts,服務裏面new一個SubJect對象:html

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

而後,定義兩個組件one-child和two-child在app.compnent顯示:git

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

其中,one-child裏面有一個輸入框,綁定keyup方法sendText:github

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

在one-child裏面注入app.service,調用sub對象:npm

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
  ) { }
 
  sendText(value) {
    console.log("one-child: " + value);
    this.appService.sub.next(value);
  }
 
}

此時,在two-child裏面訂閱sub對象獲取數據:app

// 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 {
  
  value;
  constructor(
    private appService: AppService
  ) { }
  
  ngOnInit() {
    this.appService.sub.subscribe(res => {
      this.value = res;
      console.log("two-child: " + res);
    })
  }
}

最終咱們就能夠看到在one-child裏面輸入的數據在two-child也能夠接收到了:
圖片描述this

最後的話,對於訂閱對象,在組件銷燬的時候,根據實際狀況要取消訂閱:spa

ngOnDestroy() {
  this.appService.sub.unsubscribe();
}

demo可從下面地址下載體驗,下載後運行npm install:
https://github.com/ldpliudong...code

相關文章
相關標籤/搜索