简体   繁体   中英

angular2-jwt token.split is not a function

I have been trying to fix this error for the last 2 days but I just cannot figure out whats wrong. I am using ionic2/angular2 along with the angular2-jwt library but I keep getting an error saying token.split is not a function .

I believe it has something to do with my storage. I am using ionics Storage

I made a function to check if the token is expired

jwtHelper: JwtHelper = new JwtHelper();
token;

checkToken() {

  this.token = this.storage.get('token');
  console.log(this.token);
  //let token2 = JSON.stringify(this.token);
  //console.log(token2);
  if (this.jwtHelper.isTokenExpired(this.token))
  {
    console.log("valid");
  }
  else {
    console.log("expired");
  }
}

This is what console.log(this.token) above prints out which is why I believe the storage is the problem Object { __zone_symbol__state: null, __zone_symbol__value: Array[0] }

console

This is what is calling checkToken()

getInfo(): Observable<any> {

  this.tokenProvider.checkToken();

  return this.authHttp.get('')
    .map(
      (response: Response) => {
        return response.json().sites;
      },
      (error: Response) => {
        console.log(error);
      }
    );
}

How I set token after login

setToken(token) {
  this.storage.set('token', token);
}

app.module.ts

import {IonicStorageModule, Storage} from '@ionic/storage';
import { AuthHttp, AuthConfig} from 'angular2-jwt';

export function getAuthHttp(http, storage) {
  return new AuthHttp(new AuthConfig({
    headerPrefix: '',
    noJwtError: true,
    globalHeaders: [{'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest'}],
    tokenGetter: (() =>   storage.get('token')),
  }), http);
}

imports: [
  BrowserModule,
  IonicModule.forRoot(MyApp),
  FormsModule,
  HttpModule,
  IonicStorageModule.forRoot()
],
providers: [ 
 .....
AuthHttp,
{
  provide: AuthHttp,
  useFactory: getAuthHttp,
  deps: [Http, Storage]
},

package.json

{
  "name": "ionic-hello-world",
  "version": "0.0.0",
  "author": "Ionic Framework",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.0.2",
    "@angular/compiler": "4.0.2",
    "@angular/compiler-cli": "4.0.2",
    "@angular/core": "4.0.2",
    "@angular/forms": "4.0.2",
    "@angular/http": "4.0.2",
    "@angular/platform-browser": "4.0.2",
    "@angular/platform-browser-dynamic": "4.0.2",
    "@ionic-native/core": "3.4.2",
    "@ionic-native/splash-screen": "3.4.2",
    "@ionic-native/status-bar": "3.4.2",
    "@ionic/storage": "^2.0.1",
    "angular2-jwt": "^0.2.3",
    "ionic-angular": "3.1.0",
    "ionicons": "3.0.0",
    "ng2-completer": "^1.4.0",
    "rxjs": "5.1.1",
    "sw-toolbox": "3.4.0",
    "zone.js": "^0.8.5"
  },
  "devDependencies": {
    "@ionic/app-scripts": "^1.3.6",
    "typescript": "~2.2.1"
  },
  "cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-console",
    "cordova-plugin-statusbar",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [],
  "description": "installerApp: An Ionic project"
}

The problem is that the storage returns a promise , so you need to wait for that promise to be resolved before using the token.

checkToken(): Promise<any> {

  // We're going to return the promise, so the calling method will use it
  // to wait until the token is obtained from the storage
  return this.storage.get('token').then(token => {

    this.token = token; // Assign the token to the this.token property

    console.log(this.token);

    //let token2 = JSON.stringify(this.token);
    //console.log(token2);

    if (this.jwtHelper.isTokenExpired(this.token)) {
      console.log("valid");
    } else {
      console.log("expired");
    }

  });

}

And then

getInfo(): Observable<any> {

  // The checkToken method returns a promise, so we're going to
  // create an observable with it, and then use the 'flatMap' operator
  // in order to make the get request only if the token is ready

  return Observable.fromPromise(this.tokenProvider.checkToken())
                   .flatMap(() => {

                     // Here the token is ready!

                     return this.authHttp.get('').map(
                       (response: Response) => {
                         return response.json().sites;
                       },
                       (error: Response) => {
                         console.log(error);
                       });
                   });

}

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