Ionic 4 - 将令牌的承诺转换为可观察的?

Ionic 4 - convert promise for token to observable?

我正在尝试提交 post,并发送带有 header 的令牌。但是我的 storage.get returns 一个承诺,我不知道如何从 storage.get 中获取令牌的值。我认为将它转换为 observable 可能会有所帮助,但我不知道该怎么做。

  sendPostRequest() {
    var token: string;
    this.storage.get('ACCESS_TOKEN').then((val) => {
      token = val;
    });
    const headers = new HttpHeaders()
    .set('Accept', 'application/json')
    .set('Content-Type', 'application/json')
    .set('Authorization',  'Bearer ' + token)
    .set('responseType', 'text');
    let postData = this.signatureForm.value;
    this.httpClient.post("http://localhost:3000/signature", postData, { headers: headers })
      .subscribe(data => {
        this.presentToast();
      }, error => {
          this.showError = true;
          this.errorMessage = error.error.message
    });
  }

鉴于 storage.get() 是异步的,您应该在 then 块中处理后续操作。这将防止 token 成为 undefined 的问题,因为您需要等待 storage.get() 的承诺被返回。

sendPostRequest() {
    var token: string;
    this.storage.get('ACCESS_TOKEN').then((val) => {
      token = val;

      const headers = new HttpHeaders()
        .set('Accept', 'application/json')
        .set('Content-Type', 'application/json')
        .set('Authorization',  'Bearer ' + token)
        .set('responseType', 'text');

        let postData = this.signatureForm.value;
        this.httpClient.post("http://localhost:3000/signature", postData, { headers: headers })
          .subscribe(data => {
            this.presentToast();
          }, error => {
            this.showError = true;
            this.errorMessage = error.error.message
          });
    });

  }

但是,如果您想使用 Angular/RxJS 方式来实现,您可以使用 RxJS from operator. Then, the subsequent assignment of token and the returning of the post request can be handle within pipeable operators, such as switchMap.

将 promise 转换为可观察对象
from(this.storage.get('ACCESS_TOKEN'))
  .pipe(
     switchMap((val) => {
       token = val;
       // do the rest here
       // return this.httpClient.post()
     }),
   ).subscribe(data => {
     this.presentToast();
   }, error => {
     this.showError = true;
     this.errorMessage = error.error.message;
   });

你必须在你的承诺的成功回调中实现逻辑,就像这样:

    sendPostRequest() {
      var token: string;
      this.storage.get('ACCESS_TOKEN').then((val) => {
        this.postSignature(val);
      });
    }

    private postSignature(token: string) {
    const headers = new HttpHeaders()
         .set('Accept', 'application/json')
         .set('Content-Type', 'application/json')
         .set('Authorization',  'Bearer ' + token)
         .set('responseType', 'text');
    let postData = this.signatureForm.value;
    this.httpClient.post("http://localhost:3000/signature", postData, { headers: headers })
         .subscribe(data => {
           this.presentToast();
         }, error => {
          this.showError = true;
          this.errorMessage = error.error.message
         });
    }

Promise 是异步的,这意味着在完成请求之前您没有令牌值,这就是为什么您需要在成功回调中实现逻辑。