从Ionic 2存储设置构造函数中的属性值

时间:2017-04-13 03:13:42

标签: angular ionic-framework ionic2

我有一个服务,我从服务器检索数据,然后通过POST数据发送一个令牌。问题是,令牌存储在本地存储中,我尝试将其分配给我的服务类中的令牌属性,但它根本不起作用(没有错误或任何东西)。这是我的代码的样子:

import {Injectable} from '@angular/core';
import  { Http, Headers } from '@angular/http';
import { Storage } from '@ionic/storage';
import 'rxjs/Rx';

@Injectable()
export class MyData {
    http: any;
    baseUrl: String;
    token: String;

    constructor(
        http: Http,
        public storage: Storage){
            this.http = http;
            this.baseUrl = 'http://192.168.0.109:8000';
            this.storage.get('token').then((value) => {
                this.token = value;
            });
    }

    getTickets(){
        console.log(this.token); // Doesn't show the token, I know it's in storage I have verified through other means
    }
}

我从我的一个页面ts文件中调用getTickets(),如下所示:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { MyData } from '../../providers/my-data';
import { Storage } from '@ionic/storage';


@IonicPage()
@Component({
  selector: 'page-account',
  templateUrl: 'account.html',
})
export class AccountPage {
  token: String;
  events: any;

  constructor(
    public navCtrl: NavController,
    public myData: MyData,
    public navParams: NavParams,
    public storage: Storage) {
  }

  ionViewDidLoad() {
    this.myData.getTickets().subscribe(response => {
      console.log(response);
    });
  }

1 个答案:

答案 0 :(得分:0)

你的代码是正确的,值也会出现,这里唯一的问题是在将任何值分配给令牌之前调用getTickets()方法。

因此从AccountPage传递令牌值。这将解决问题。