angular2-jwt token.split 不是函数

标签 angular typescript ionic2

过去 2 天我一直在尝试修复此错误,但我无法弄清楚问题出在哪里。我正在使用 ionic2/angular2 和 angular2-jwt库,但我不断收到一条错误消息,提示 token.split is not a function

我相信这与我的存储有关。我正在使用 ionics Storage

我做了一个函数来检查 token 是否过期

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

这就是 console.log(this.token) 上面打印出来的内容,这就是为什么我认为存储是问题所在 Object { __zone_symbol__state: null, __zone_symbol__value: Array[0] }

console

这就是调用 checkToken()

getInfo(): Observable<any> {

  this.tokenProvider.checkToken();

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

登录后如何设置token

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

应用程序模块.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]
},

包.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"
}

最佳答案

问题在于存储会返回一个promise,因此您需要等待该 promise 得到解决,然后才能使用 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");
    }

  });

}

然后

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

}

关于angular2-jwt token.split 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44272453/

相关文章:

css - 如何在ionic 3中进行水平滚动

http - Angular2 Observable HTTP 数据未填充

angular - 如何在 Angular 7 中对 getCurrentNavigation().extras.state 进行单元测试

Typescript:推断函数参数

google-maps-api-3 - 如何在 ionic2 中将标记移动到 map 上?

html - 如何在 Angular4 中添加由某些用户输入定义的自定义 CSS?

Angular http 请求在 chrome 中返回 null,但在 firefox 中有效

javascript - ionic 2 ion-datetime ISO格式问题

http - ionic 2/Angular 2/CORS : HTTP Headers not being sent with request

html - ionic 2的垂直下拉导航