简体   繁体   English

将Observable.subscribe()返回的值赋给const

[英]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. 我正试图从Ionic4-Angular前端向我的Django API发送请求,问题是我还没有熟悉这个技术甚至是javascript。 In the following code I'm trying to return the subscribe data and assign it to a const. 在下面的代码中,我试图返回订阅数据并将其分配给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. 第一个console.log包含我要搜索的真实对象。 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 . 此方法使用switchMap运营商只要求http.post一次authService.getToken返回token.You可以找到文件的所有RxJs运营商这里

callback function of subscribe cannot return any value to user . subscribe回调函数不能向user返回任何值。 it only gets Subscriber object as you mentioned which is result of observable. 它仅获得您提到的Subscriber对象,这是可观察的结果。

If you want to use async , await approach, you need to use toPromise method to make an observable a promise. 如果要使用asyncawait方法,则需要使用toPromise方法作出可观察的承诺。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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