问题
Variables inside subscribe are undefined but when i put breakpoint before hitting service subscribe I have the variable defined.
In Service:
getCashierRiskProfiles(): Observable<ICashierRiskProfile[]> {
return this.http.get(this._baseUrl + "src/HTTPJson/cashierriskprofile.json")
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
In Component:
import { Component, OnInit} from "@angular/core";
import { CashierRiskProfileService} from "./cashierriskprofile.service";
import { ICashierRiskProfile} from "../shared/interfaces";
import { Observable } from 'rxjs/Observable';
@Component({
selector: "cashierriskprofile",
templateUrl: "../src/app/cashierriskprofile/cashierriskprofile.component.html"
})
export class CashierRiskProfileComponent implements OnInit {
filterText : string;
cashierRiskProfiles: ICashierRiskProfile[];
constructor(private sorter: Sorter,
private service: CashierRiskProfileService) {
}
ngOnInit() {
this.filterText = "Filter Exceptions:";
//// Observable technique
this.service.getCashierRiskProfiles()
.subscribe((riskProfiles) => {
this.cashierRiskProfiles = riskProfiles;
this.filterText = "Inside Subscribe:";
},
err => {
// Log errors if any
console.log(err);
});
}
In above component code inside ngonInit() service call, this.cashierRiskProfiles inside the subscribe is undefined, but after I put breakpoint before the service callI have that variable available and defined. I have seen lot of people having this issue with component variables with this.variablename gettting undefined inside subscribe. When you notice this.filterText I can get the values assigned to it outside dataservice call, but when I put breakpoint inside subscribe, this.filterText is underfined dont know how I am losing it. Can anyone provide solution of what's going on ?
回答1:
I guess it's because during runtime this inside subscribe is SafeSubscribe, not your component.
use closure to call component method, like this:
populateCashierRiskProfiles() {
const that = this;
//// Observable technique
this.service.getCashierRiskProfiles()
.subscribe((riskProfiles) => {
that.cashierRiskProfiles = riskProfiles
});
}
回答2:
Your code looks good to me. I'm following the same approach in my project and working fine for me
anyways you can try the following and let me know if it works fine
ngOnInit() {
this.filterText = "Filter Exceptions:";
this.populateCashierRiskProfiles();
}
populateCashierRiskProfiles() {
//// Observable technique
this.service.getCashierRiskProfiles()
.subscribe((riskProfiles) => {
this.cashierRiskProfiles = riskProfiles
});
}
来源:https://stackoverflow.com/questions/39899595/component-variables-inside-a-rxjs-subscribe-function-are-undefined