Получить токен из хранилища Ionic (Async data) - PullRequest
0 голосов
/ 31 октября 2018

Как получить доступ к токену, хранящемуся в памяти мобильного телефона, поскольку он получается асинхронно. Переменная всегда неопределена.

Это .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;
        }
      });         
  }
}

Это служба, в которой я хочу сначала получить доступ к токену, а затем посмотреть его. Переменная token всегда отображается как 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;
      }); 
  })     
 }

Пустота

1 Ответ

0 голосов
/ 31 октября 2018

Хорошо, поскольку ваш код сложен для понимания, я хотел бы поделиться с вами информацией о том, как бы я его организовал, обратите внимание, что я еще не знаю, какой модуль 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})
    }

}

Теперь в ваших cars.ts:

// 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...