离子本地存储未获取数据

时间:2019-01-02 02:31:39

标签: angular ionic3 ionic-storage

我试图获取使用离子存储器存储的令牌,并将其存储在全局变量public token = ''中。但是每次我使用this.token访问它时,值都不会改变。

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';

const TOKEN_KEY = 'access_token';

@Injectable()
export class ContactProvider {

  public url = 'myapi-link';
  public token = '';


  constructor(
    private storage: Storage,
    private http: HttpClient
  ) {

  }

  loadToken(){

    this.storage.get(TOKEN_KEY).then((token)=>{
      this.token = token;
      console.log(this.token);
    });

  }

  setHeaders(default_content_type = 'application/json'){

    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', default_content_type)
    .set('Authorization', 'Bearer ' + this.token)
    return headers;

  }

  getData(type){

    this.loadToken();
    let headers = this.setHeaders();
    return this.http.get(this.url + type, {headers: headers});

  }

}

调用this.setHeaders()时,this.token不变。

2 个答案:

答案 0 :(得分:1)

就像其他人指出的那样,您需要了解承诺的工作方式。 这是怎么做的: 1:LoadToken需要返回承诺:

loadToken(){
    return this.storage.get(TOKEN_KEY);
}

注意 return 关键字,该关键字将返回storage.get()返回的promise

2:兑现承诺并等待其完成,然后再继续:

async getData(type){
    this.token = await this.loadToken();
    let headers = this.setHeaders();
    return this.http.get(this.url + type, {headers: headers});
}

请注意getData方法名称前面的 async 关键字,它指示您将等待在其中完成承诺。 然后 await 关键字,它将确保仅在promise解决后才执行其余代码。

由于承诺也可以被拒绝,因此您需要执行以下操作:

async getData(type){
  try {
    this.token = await this.loadToken();
    let headers = this.setHeaders();
    return this.http.get(this.url + type, {headers: headers});
  } catch (error) {
     //Handle your error here
  }
}

答案 1 :(得分:0)

在loadToken中调用setHeaders,因为它异步返回数据,

package gExample;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.Timer;


public class GraphicsExample extends Canvas implements ActionListener {

private final static int HEIGHT = 600; 
private final static int WIDTH = 600; 
private int n = 0;
private int x, y;
Timer t = new Timer(20, this);

public static void main(String args[]) {
    JFrame frame = new JFrame();
    GraphicsExample canvas = new GraphicsExample();

    canvas.setSize(WIDTH, HEIGHT);
    frame.add(canvas);
    frame.pack();
    frame.setVisible(true);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    canvas.setBackground(Color.black);
}

public void paint(Graphics g){ 
    Random rand = new Random();

    Color col = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
    g.setColor(col);

       /*each time paint() is called, I expect a new circle to be printed in the
        x and y position that was updated by actionPerformed(), but only one inital circle is created. */
    g.fillOval(x, y, 8, 8);

    t.start();

}


@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

    int c = 9;
    double r = c * Math.sqrt(n);
    double angle = n * 137.5;

    //here, every time the method is called, the x and y values are updated, 
   //which will be used to fill in a new circle
    int x = (int) (r * Math.cos(angle * (Math.PI / 180) )) + (WIDTH / 2);
    int y = (int) (r * Math.sin(angle * (Math.PI / 180) )) + (HEIGHT / 2);

    //when the program is running, this line of code is executed multiple times.
    System.out.println("x: " + x + " y: " + y);

    n++;

}




}