Angular 2 Cannot read property "subscribe" undefined TypeError: Cannot read property "subscribe" undefined
I've tried many suggestions to fix this error here on stackoverflow, but now I just need to ask how I spent many hours literally losing nowhere.
I have this simple service:
constructor(private http: Http, private tokenResolver: TokenResolver) {}
public getEventHistory(): Observable<heatmapElement[]> {
this.tokenResolver.getToken(true).subscribe(token => {
var headers = new Headers();
headers.append('Authorization', 'Bearer ' + token);
headers.append('Content-Type', 'application/json');
this.result = this.http.get(this.restApi, new RequestOptions({headers: headers}))
.map((res: Response) => res.json());
});
return this.result as Observable<heatmapElement[]>;
}
I want to get data using:
public demoData: heatmapElement[] =[];
getEventHistory(): void {
this.eventHistoryService.getEventHistory()
.subscribe(data => this.demoData = data,);
}
This creates an error that I just cannot fix:
EXCEPTION: Unprepared (in promise): Error: Error http: // localhost: 5555 / app / dashboard / dashboard.html: 13: 8 caused by: Unable to read property "subscribe" undefined TypeError: Unable to read property "subscribe" undefined
I would be very grateful for your help, thanks
source to share
you cannot return a result async call
outside of its method subscribe
.
If you want to return Observable from getEventHistory()
, you can change subscribe
to map
or switchMap
.
public getEventHistory(): Observable<heatmapElement[]> {
return this.tokenResolver.getToken(true).switchMap(token => {
var headers = new Headers();
headers.append('Authorization', 'Bearer ' + token);
headers.append('Content-Type', 'application/json');
return this.http.get(this.restApi, new RequestOptions({headers: headers}));
})
.map((res: Response) => res.json() as heatmapElement[]);
}
source to share
Odd how it might be, in my case, after a lot of debugging time, it turns out that I was using the Output ( @Output
) property EventEmitter
to handle a custom event, and Angular recognize my property or custom event property when passed by template:
eg
<custom-component (keydownEvent)="someFunctoin()"></custom-component>
The problem with doing the above (as far as my problem is concerned) is (keydownEvent)
not a valid Event handler, but why does it work in development and not when you created your project. Even MORE strange, it ng build --prod
doesn't throw any errors or warnings!
Decision
<custom-component keydown="someFunctoin()"></custom-component>
Where do the subscription / subscription errors occur?
Well, what do you think one subscribed to EventEmitter
- so I guess where the correlation is
source to share