Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
            });
      }
    });
}
like image 778
ghan Avatar asked Dec 24 '22 17:12

ghan


1 Answers

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;
}
like image 117
Saravana Avatar answered Dec 26 '22 07:12

Saravana