Answer the question
In order to leave comments, you need to log in
Angular subscribe(): Cannot read property 'subscribe' of undefined?
The service sends data to the subscription in the wrong format, help bring it to the desired form.
Service
getStats() {
let statsLS = localStorage.getItem('stats');
let slt = +localStorage.getItem('slt');
let date = new Date();
let time = date.getTime();
if(statsLS === null || slt < time) {
this.http.get('/server/api/statsService').subscribe((data: any) => {
this.stats = data;
let date = new Date();
let time = date.getTime()+60000+'';
localStorage.setItem('stats',JSON.stringify(this.stats));
localStorage.setItem('slt',time);
return this.stats;
});
} else {
return JSON.parse(statsLS);
}
}
}
ngOnInit() {
this.statsService.getStats().subscribe((data: any) => console.log(data));
}
Answer the question
In order to leave comments, you need to log in
You don't return anything at all in the getStats() code.
You are returning data from a function that is your http.get subscriber.
As far as I remember, you need to declare an object of type Observable() inside getStats() and return it. Something like this in general:
getStats()
{
return new Observable<any>((observer) => {
let statsLS = localStorage.getItem('stats');
let slt = +localStorage.getItem('slt');
let date = new Date();
let time = date.getTime();
if (statsLS === null || slt < time) {
this.http.get('/server/api/statsService').subscribe((data: any) => {
this.stats = data;
let date = new Date();
let time = date.getTime() + 60000 + '';
localStorage.setItem('stats', JSON.stringify(this.stats));
localStorage.setItem('slt', time);
observer.next(this.stats);
});
} else {
observer.next(JSON.parse(statsLS));
}
});
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question