I have a service method which gets dummy data and returns an observable.
private dummySubject = new BehaviorSubject<Dummy>(null);
dummy$ = this.dummySubject.asObservable();
loadDummyData(id: string): Observable<Dummy> {
const BASE_URL = 'someurl/' + id;
return this.http.get<Dummy>(BASE_URL).pipe(
tap((dummyData: Dummy ) => {
console.log('In Service ', dummyData); //LOGS DATA HERE
this.dummySubject.next(dummyData);
})
);
}
In another service, I use the switchMap operator to map a user id into my loadDummyData
method.
anotherService
loadDummyData(){
this.dummyService.user$.pipe(
switchMap((user: User) => {
return this.dummyService.loadDummyData(user.id);
})
).subscribe();
}
Then in my getData component
localData: Dummy;
dummy$: Observable<Dummy> = this.dummyService.dummy$;
ngOnInit() {
1) this.anotherService.loadDummyData(); //Causes data to be loogged in service
2) this.dummyService.loadDummyData('12345').subscribe( //causes data logged in service
(dummy: Dummy) => {
this.localProfile = dummy;
console.log(this.localProfile, 'data in component'); //local data log
},
err => {
console.error(err);
}
);
console.log(this.localProfile, 'In ngOnint'); //undfiened
}
In the getData component
, I make 2 calls to the dummyService method,
- call anotherService => loadDummyData() (which uses switch map to load data)
- Call dummyService => loadDummyData() directly passing an Id and subscribing.
both times the data is logged in the console and seems to be coming back. However, in my template, the async |
is not displaying the data.
The loadProfile
variable is also getting undefined in the second call to get the data.
Template
<div *ngIf="dummy$ | async as dummyData">
<span class="pull-right" *ngIf="dummyData.canViewAdmin">
<a (click)="openChangeUserModal()">Change user</a>
</span>
<p>{{dummyData.name}}</p>
</div>
What am I missing here?