[英]Angular Observable & Subject not getting the data
我在角度方面很新。
我創建了以下一項服務。
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class WizardDataService {
constructor() { }
private txtBxServiceID=new Subject<any>();
setTxtBxServiceID(value:any){
this.txtBxServiceID.next({txtBxServiceID:value});
}
getTxtBxServiceID(): Observable<any> {
return this.txtBxServiceID.asObservable();
}
}
我在表單提交的另一個組件中設置txtBxServiceID
值。 如下。
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import {WizardDataService} from '../services/wizard-data.service'
@Component({
selector: 'app-discover-device',
templateUrl: './discover-device.component.html',
styleUrls: ['./discover-device.component.scss']
})
export class DiscoverDeviceComponent implements OnInit {
discoverDeviceComponentForm: FormGroup;
isSubmitted = false;
constructor(private router: Router, private formBuilder: FormBuilder,private wizardDataService : WizardDataService) { }
ngOnInit() {
this.discoverDeviceComponentForm = this.formBuilder.group({
txtBxServiceID: ['', Validators.required]
});
}
get formControls() { return this.discoverDeviceComponentForm.controls; }
dicoverDevice(){
this.isSubmitted=true;
if(this.discoverDeviceComponentForm.invalid){
return;
}
this.wizardDataService.setTxtBxServiceID(this.discoverDeviceComponentForm.value.txtBxServiceID);
this.router.navigateByUrl('mits-update/device-details');
}
}
現在,我正在嘗試訪問另一個組件上的服務。 像下面。
import { Component, OnInit} from '@angular/core';
import {WizardDataService} from '../services/wizard-data.service';
@Component({
selector: 'app-device-mits-update',
templateUrl: './device-mits-update.component.html',
styleUrls: ['./device-mits-update.component.scss']
})
export class DeviceMitsUpdateComponent implements OnInit {
txtBxServiceID:any="";
constructor(private wizardDataService:WizardDataService) {
this.wizardDataService.getTxtBxServiceID().subscribe(value =>{
this.txtBxServiceID=value.txtBxServiceID;
});
}
ngOnInit() {
}
}
然后我在HTML上顯示此值,例如
<td>Service Id</td>
<td>{{txtBxServiceID}} </td>
我的問題是該值未在此處顯示。 那么有人可以在這里幫助我找到我在這里犯的錯誤嗎?
根據Daniel的建議,您可以使用BehaviorSubject。 但是,它需要一個初始值。 由於您沒有提供任何值,因此可以使用ReplaySubject
。
private txtBxServiceID = new ReplaySubject<any>(1);
您有一個簡單的Subject
。 僅在第一個組件設置了值之后,您才能在新組件中訂閱它。 Subject
不會將以前的值重播給新訂戶。 它還不保存最新值,並將其發送給新訂戶。
最有可能的是,您需要一個BehaviorSubject
,它將存儲最新值並將其發送給新訂戶。
如果要將所有以前的值發送給新訂閱者,則需要使用ReplaceSubject
。
因此,請使用以下代碼代替現在的代碼:
private txtBxServiceID = new BehaviorSubject<any>(null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.