Reputation: 516
Can anyone please help me and tell me why is my observable empty?
class
ionViewWillEnter(): void {
this.notificationsSvc.fetchNotifications();
}
ngOnInit(): void {
this.notificationSubscription = this.notificationsSvc.notifications.subscribe(
(data) => {
console.log(data) //this is empty
}
);
}
service
import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs";
import { HttpClient } from "@angular/common/http";
import { tap } from "rxjs/operators";
@Injectable()
export class NotificationsService {
private _notifications = new BehaviorSubject({});
constructor(private httpClient: HttpClient) {}
get notifications() {
return this._notifications.asObservable();
}
fetchNotifications() {
return this.httpClient
.get("https://website.com/notifications.json")
.pipe(tap((data) => this._notifications.next(data)));
}
}
'notifications' getter always returns empty. I'm not sure what else to do...
Upvotes: 0
Views: 1410
Reputation: 1523
An observable doesn't produce results unless you subscribe to it, so you need to subscribe to the Observable from fetchNotifications(), like this:
ionViewWillEnter(): void {
this.notificationsSvc.fetchNotifications().subscribe();
}
P.S. In order to avoid this kind of issues, I would highly recommended specifying parameter and return types of your functions and fully utilizing Typescript.
Upvotes: 3