0

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

1
  • 1. are u getting any error? if yes show us, 2. are u sure u getting the reponse from the server? Commented Aug 16, 2019 at 3:00

2 Answers 2

1

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<...>()
Sign up to request clarification or add additional context in comments.

Comments

0

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
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.