从存储Ionic获取令牌(异步数据)

时间:2018-10-30 22:08:38

标签: angular ionic-framework

由于它是异步获取的,因此如何访问手机存储中存储的令牌。该变量始终未定义。

这是我要获取数据的.ts。

cars.ts:

import { Component } from '@angular/core';
import { NavController, MenuController } from 'ionic-angular';
import { ServiceRestProvider } from '../../providers/service-rest/service-rest';
import { LoadingController } from 'ionic-angular';
import { AlertController} from "ionic-angular";


@Component({
  selector: 'page-data',
  templateUrl: 'data.html'
})
export class ResumenCooperativaPage {
  cars: any;
  constructor(public service: SProvider,
    public loadingController: LoadingController) {
    this.getData();

  }

  getData() {
    this.service.getCars()
      .subscribe(data => {
        if (data.error) {
          console.log(data.error);
        } else {
          this.cars = data;
        }
      });         
  }
}

这是我首先要访问令牌然后查看令牌的服务ts。标记变量始终显示为undefined。 service.ts

getToken(){
    return new Promise(resolve => {
      this.storage.get('Token').then((val) => {   
        resolve(val);  
        console.log('Your token is', val);  
      }); 
    });
  }

    getCars() {
      this.data= this.getToken();
      const hd = new HttpHeaders().set('Authorization', this.data)
      .set('Authorization', 'Bearer ' + this.data);
     return this.http.get(url, { headers: hd})
      .map((response) => {
          return response;
      });  
  }

更新:

更改后的消息:

[ts] Property 'subscribe' does not exist on type 'void'.

getCars() {
      this.getToken().then(token=>{
          this.data = token;
          const hd = new HttpHeaders().set('Authorization', this.data).set('Authorization', 'Bearer ' + this.data);
          return this.http.get(url, { headers: hd}).map((response) => {
          return response;
      }); 
  })     
 }

Void

1 个答案:

答案 0 :(得分:0)

好的,因为您的代码难以理解,所以我想与您分享如何组织代码,请注意,我尚不知道您使用的是哪个http模块,并且现代(4.3 +角度)模块之间存在差异和旧的。我在写下面的书时考虑到了现代的意思:

在rest-service.ts中(假设您将导入到组件中):

// do all of your specific imports here:
import { Injectable } from '@angular/core';
import { Storage } from "@ionic/storage";

@Injectable()
export class RestService {

    // cache token here to use in your restful calls:
    userToken: string;

    constructor (

    ) {
      // obtain token once during service instantiation, service providers don't have lifecycle hooks but it is OK to do init values inside the constructor:
      this.getToken();
    }

    // this will get called once with constructor execution:
    getToken() {
      this.storage.get('Token').then((token) => {   
        this.userToken = token; 
      }); 
    };

    getCars() {
      // depending on your HTTP module used in Ionic (Angular < 4.3 or > 4.3):
      // only set Authorization property in header once:
      const headers = new HttpHeaders().set('Authorization', 'Bearer ' + this.userToken);
      // so http requests will return observables (if Angular 4.3 HttpClient module is used), you will subscribe to it in your components:
      return this.http.get(url, { headers: headers})
    }

}

现在在你的车上。

// do your proper imports here:
import { Component } from '@angular/core';
import { NavController, MenuController } from 'ionic-angular';
import { RestService } from '../../app/providers/rest-service';
import { LoadingController } from 'ionic-angular';
import { AlertController} from "ionic-angular";

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  // component var that will get assigned values:
  cars: Array<string> = [];

  constructor(public restService: RestService, public loadingController: LoadingController) {

  }
  // this life cycle hook is only called once when component enters memory, feel free to use other hooks as needed for your app, but key thing is that you call method in provider and subscribe/unsubscribe in components.
  ionViewDidLoad() {
    // here on component load into memory you can call the method:
    this.restService.getCars().subscribe((carsData) => {
        this.cars = carsData;
      }, (error)=>{
        console.log(error);
      });  
  }

}

您的模板可以是这样:

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>Welcome to Cars Page!</h2>
  <ion-list>
    <ion-item *ngFor="let car of cars">
      <ion-label>{{ car.title }}</ion-label>
    </ion-item>
  </ion-list>
</ion-content>