I have problem with Observables in Angular2, which always results in a "Cannot read property 'subscribe' of undefined" the first time the code is called.
I have a service called FieldService, which a getFields method:
getFields(): Observable<any>{
console.log("FieldService getFields");
let fields = JSON.parse(localStorage.getItem('organisationFields') || 'null');
if(!fields) {
this._backendService.get(this.fieldsUrl).subscribe(response=> {
let fields = response.data;
console.log("FieldService no local fields");
localStorage.setItem('organisationFields', JSON.stringify(fields));
return Observable.of(fields).map(o => o);
}, error => {
console.error('FieldsService An error occurred', error);
return Observable.throw(error);
});
} else {
console.log("FieldService local fields")
return Observable.of(fields).map(o => o);
}
}
It checks to see if there are any "fields" in the local storage and return these as an Observable, if there are none (first time login) we go a fetch these from the backend and stores these on the localStorage.
This service is the used in my ListComponent.ts in ngOnInit:
this.fieldService.getFields().subscribe( (response) => {
let fields = response;
this.fieldObjects = {};
for(let fieldIndex of fields){
this.fieldObjects[fieldIndex.id] = fieldIndex;
}
this.getDeviations(this.page, this.config.stage.id, this.config.createdBy);
}, error => {
console.error('An error occurred', error);
});
I need to have the getFields() method called before I can call the getDeviations(), but I get this error:
ERROR TypeError: Cannot read property 'subscribe' of undefined
at ListComponent.webpackJsonp.../../../../../src/app/deviation/list.component.ts.ListComponent.ngOnInit (list.component.ts:38)
If the "fields" exists in the localStorage - the code works everytime, but if I clear the localStorage and need to go and get them for the first time I get the error. What is wrong?
nextanderrorhandlers passed tosubscribe. That's just not how it works.nextanderror. Where is my error? Fixed the indentation