Reputation: 21
I am a beginner of angular. While i tried to retrieve data using AngularFireDatabase object, i am not getting the data in the required format
Interface:
export interface AppUser {
name: string;
email: string;
isAdmin: boolean;
}
Function call:
get appUser$():Observable<AppUser>{
return this.user$.pipe(
map(user=> this.userService.get(user.uid)))
}
userService.ts
import { Injectable } from '@angular/core';
import {AngularFireDatabase, AngularFireObject} from angularfire2/database';
import * as firebase from 'firebase';
import {Observable} from 'rxjs/Observable'
import { AppUser } from './models/app-file';
import { AngularFireAuth } from 'angularfire2/auth';
import { map, switchMap } from 'rxjs/operators';
get (uid : string){
let result={};
this.userdetails = this.db.object('/users/'+uid).valueChanges();
return this.userdetails;
}
ERROR in src/app/auth.service.ts(40,6): error TS2322: Type 'Observable>' is not assignable to type 'Observable'. Type 'Observable' is missing the following properties from type 'AppUser': name, email, isAdmin
Upvotes: 0
Views: 608
Reputation: 535
All your core functionality, for example, getting data from the database, your auth guards should be in a separate module. I Use to call it Core Module. I'm writing this because you have mentioned that you are a beginner. So for this case, nn your service file do this:
getDataFromDb(uid) {
return this.db.object('/users/'+ uid).valueChanges();
}
The method is just getting the data under users' node from firebase. The method valueChanges()
it self returns an observable of type Observable<any[]>
Now inside your component's ts file, you should subscribe to that observable and assert that value to whatever type or interface you have defined.
and in your ts file:
export class Component() {
result: AppUser;
constructor(private service: Service) {}
dataFromService() {
this.userService.getDataFromDb(user.uid).subscribe((res: any) => {
this.result = res;
})
}
}
What you are currently doing in you ts file is that you are using map
operator which would not emit the value unless you subscribe to it. And in your case, you don't even have to use pipe
. Just use subscribe
to get the value form the observable. Read the docs for better understanding:
https://github.com/angular/angularfire2/blob/master/docs/rtdb/objects.md
Upvotes: 1