简体   繁体   中英

Assign value returned by Observable.subscribe() to a const

I'm trying to send a request to my Django API from an Ionic4-Angular front-end, the problem is that I've not become familiar with this tecnology or even javascript yet. In the following code I'm trying to return the subscribe data and assign it to a const.

async getUserLogged() {
    const tkn = await this.authService.getToken();
    const user = await this.http
      .post('http://localhost:8000/api/getuser/', {
        token: tkn
      })
      .subscribe(response => {
        console.log(response);
        return response;
      });
    console.log(user);

    return user;
  }

The first console.log contains the real object i'm searching for. However, the second one prints a Subscriber object. Can anyone explain me this behaviour and how can I fix it

Here is how I would set up this method:

getUserLogged() {
  return this.authService.getToken().pipe(
    switchMap(tkn=> {
      return this.http.post('http://localhost:8000/api/getuser/', {
        token: tkn
      })
   })
  );
}

You then use this method as follows:

getUserLogged().subscribe(userData => console.log(userData));

This approach uses the switchMap operator that only calls http.post once authService.getToken returns the token.You can find the documentation to all RxJs operators here .

callback function of subscribe cannot return any value to user . it only gets Subscriber object as you mentioned which is result of observable.

If you want to use async , await approach, you need to use toPromise method to make an observable a promise.

async getUserLogged() {
    const tkn = await this.authService.getToken();
    const user = await this.http
      .post('http://localhost:8000/api/getuser/', {
        token: tkn
      }).toPromise();
    console.log(user);

    return user;
  }

Converting your observable response to a promise, makes it easy to call from where you need.

const getUserLogged = () => {
    const tkn = await this.authService.getToken();
    return this.http
      .post('http://localhost:8000/api/getuser/', {
        token: tkn
      })
      .toPromise();
};

const someOtherFunc = async () => {
  const user = await getUserLogged();
  console.log({ user });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM