[英]Angular: Share data dynamically between components using RxJs/BehaviorSubject
我有兩個同級組件,並排顯示,例如Component-A和Component-B。
組件A具有表單控件,一旦用戶填寫了表單,我就需要執行一些業務邏輯並將數據顯示到組件B中。
我已經創建了共享數據的服務。 當前,當用戶進行任何更改但數據不會自動顯示時,組件B中的數據可用,我在組件B上放置了“刷新”按鈕,並且當我單擊該按鈕時,正在顯示數據。
我要實現的是從組件A到組件B的流暢數據流,而無需用戶單擊。 由於某種原因,我無法在組件B中訂閱該服務。
使用@angular版本〜4.0.0
Nav.Service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class NavService {
// Observable navItem source
private _navItemSource = new BehaviorSubject<string>(null);
// Observable navItem stream
navItem$ = this._navItemSource.asObservable();
changeNav(query: string) {
this._navItemSource.next(query);
console.log("Inside changeNav",query )
}
}
組件-A
Private getSelectedComponents() {
this._navService.changeNav(this.searchValue) //dataFromControls is string data..
this.dataFromSisterComponent = '';
}
HTML:
<div class="form-group">
<div class="form-inline">
<label for="searchbox" class="control-label">Search : </label>
<input id="searchbox"class="form-control" type="text" #searchValue (keyup)="0"/>
<button class="btn btn-success" (click)="getSelectedComponents()">Add</button>
</div>
</div>
組件-B
import { Component, Input, Output, EventEmitter, ViewChild, OnInit, OnDestroy} from '@angular/core';
import { FormControl, FormGroup} from '@angular/forms';
import { DataService} from '../../Services/DataService/data.service';
import { Subscription } from 'rxjs/Subscription';
import { NavService } from '../../Services/NavService/nav.service';
@Component({
moduleId: module.id,
selector:'ComponentB',
templateUrl: 'Component-B.component.html',
})
export class Component-B implements OnInit {
subscription: Subscription;
dataFromComponentA: string;
shows: any;
error: string;
item: string;
constructor(private dataService: DataService,private _navService: NavService)
{
}
ngOnInit() {
this.getQuery();
}
getQuery() {
this.subscription = this._navService.navItem$
.subscribe(
item => this.item = item,
err => this.error = err
);
dataFromComponentA=this.item
console.log("Inside getquery",this.item )
}
ngOnDestroy() {
this.subscription.unsubscribe();
console.log("ngOnDestroy")
}
}
HTML
在html下面,當用戶在ComponentA中進行更改時,我想自動在{{dataFromComponentA}}中顯示數據。 當我單擊“刷新”按鈕時,當前正在顯示數據,並且我希望避免單擊此按鈕。
<h3>Template Components 123 </h3>
<button class="btn btn-success" (click)="getQuery()">Refresh</button>
<p><b>Value coming from Component-A</b>
{{ dataFromComponentA }}
OK </p>
您需要傳遞給subscribe
的回調中的代碼
getQuery() {
this.subscription = this._navService.navItem$
.subscribe(
item => {
this.item = item,
dataFromComponentA=this.item
console.log("Inside getquery",this.item )
},
err => this.error = err
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.