Typescript Angular2 errors when returning a promise and creating an observable from it

房东的猫 提交于 2020-01-02 08:18:47

问题


I am attempting to retrieve a token from ionics storage in getToken()and than use it in refreshToken() to see if the token is expired by passing it to (this.jwtHelper.isTokenExpired(this.token) which returns a true or false depending on if the token is expired or not. I have put comments in refreshToken() where I am getting the following errors

Error 1:

Error: TS2345:Argument of type '(response: Response) => void' is not assignable to parameter of type '(value: Response) => void'. Types of parameters 'response' and 'value' are incompatible. Type 'Response' is not assignable to type 'Response'. Two different types with this name exist, but they are unrelated. Property 'body' is missing in type 'Response'.

Error 2:

Error:(34, 46) TS2339:Property 'token' does not exist on type 'Promise<any>'.

My code

import {AuthHttp, JwtHelper, tokenNotExpired} from "angular2-jwt";
import {Observable} from "rxjs/Observable";
import {AuthService} from "../Services/Auth/auth.service";
import {Injectable} from "@angular/core";
import { Storage } from '@ionic/storage';
import {AlertController} from "ionic-angular";

@Injectable()
export class TokenProvider {

jwtHelper: JwtHelper = new JwtHelper();
token;

constructor(private authHttp: AuthHttp, private storage: Storage, private alertCtrl: AlertController) {
}

getToken(): Promise<any> {
  return this.storage.get('token').then(token => {
     this.token = token;
  });
}

refreshToken(): Observable<any> {

  return this.token = Observable.fromPromise(this.getToken())
    .flatMap(() => {
      if(this.jwtHelper.isTokenExpired(this.token))
      {
        return this.authHttp.get('localhost.api/refresh')
          .subscribe(   // ERROR 1 HERE
            (response: Response) => {
              this.token = response.json().token;  // ERROR 2 HERE
            },
            (error: Response) => {
              console.log(error);
            });
      }
    });
}

回答1:


You are not importing Response in your code. The compiler probably got confused on which Response to use as there may be multiple definitions in your typings :

import { Response } from '@angular/http';

Also, you are not returning the observable inside flatMap. You are returning the Subscription. Return the original observable like this:

refreshToken(): Observable <any> {

    let observable = Observable.fromPromise(this.getToken())
     .filter(() => this.jwtHelper.isTokenExpired(this.token))
     .flatMap(() =>  this.authHttp.get('localhost.api/refresh'));
    observable.subscribe((response: Response) => {
            this.token = response.json().token;
        }, (error: Response) => {
            console.log(error);
        });
    return observable;
}



回答2:


The refreshToken function is incorrect

  • You must not subscribe inside operators in RxJS
  • Get returns an Observable (or promise as it seems in your case)

Try the following:

refreshToken(): Observable<any> {    
  return this.token = Observable.fromPromise(this.getToken())
    .flatMap(() => {
      if(this.jwtHelper.isTokenExpired(this.token))
      {
        return this.authHttp.get('localhost.api/refresh')
      }
    })
    .catch(() => console.log(error))
    .map(response: Response => response.json())
    .subscribe(value => {
      this.token = value.token
    })
}


来源:https://stackoverflow.com/questions/44290123/typescript-angular2-errors-when-returning-a-promise-and-creating-an-observable-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!