Reputation: 125
In my service, I am able to connect to firebase realtime db and retrieve the information I want. However, when I try to call the method from a component, the result is always 'undefined'.
service.ts
async getUserSettings(userID : string) {
const firebaseToken = await
this.angularFireAuth.auth.currentUser.getIdToken(true);
let searchParams = new HttpParams();
searchParams = searchParams.set('auth', firebaseToken);
searchParams = searchParams.append('id', userID);
this.http.get<{ [userID: string]: SettingsModel }>(API.DB_URL + API.userSettings,
{
params: searchParams
})
.pipe(
map(responseData => {
let settings : SettingsModel;
for (const key in responseData) {
if (responseData.hasOwnProperty(key)) {
if(responseData[key].id === userID) {
settings = responseData[key];
}
// postsArray.push({ ...responseData[key], id: key });
}
}
return settings;
}),
catchError(errorResponse => {
return throwError(errorResponse);
})
)
.subscribe(setting => {
this.retrievedSettings = setting;
return this.retrievedSettings;
});
}
component
getUserSettings() {
const userID = this.authenticationService.getUserId();
this.userSettings = this.dbService.getUserSettings(userID)
.then(responseData => {
console.log(responseData);
});
the responseData always returns undefined
Upvotes: 0
Views: 74
Reputation: 1
Use the below strategy:
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) {}
this.http.get<any>(url).subscribe((response: any) => {
// handle the response
});
Upvotes: 0
Reputation: 23016
Your getUserSettings
doesn't have a return statement. So normally that function would return undefined
. But because this is an async
function it will return a Promise
around that undefined
.
To fix this, change the line where you do the HTTP request:
this.http.get<...>()
To return the observable that yields the value you want:
return this.http.get<...>()
Upvotes: 1