读取全局变量Ionic

时间:2019-01-10 13:10:17

标签: angular ionic-framework

我正在通过服务获取访问令牌,声明一个全局变量,并试图在另一个函数或页面中使用接收到的令牌。 但是它总是回到我身边“不确定”,我在做什么错了?

@Injectable()
export class AuthService {
public globalToken: string;

constructor(...){}

getToken() {

var request = require('request');

return request.post({
  uri: "https://api.sandbox.paypal.com/v1/oauth2/token",
  headers: {
    "Accept": "application/json",
    "Accept-Language": "en_US",
    "content-type": "application/json"
  },
  auth: {
    'user': 'xxxxxxx',
    'pass': 'xxxxxxx',
    // 'sendImmediately': false
  },
  form: {
    "grant_type": "client_credentials"
  }
}, function (error, response, body) {
  let json = JSON.parse(body);
  // console.log('token', JSON.stringify(json.access_token));
  this.globalToken = json.access_token;
  console.log('tokentoken', this.globalToken);


});


}

但是当我尝试在另一个函数中访问“ globalToken”时,返回“ undefined”。

testToken() {
this.globalToken;
console.log('testtoken', this.globalToken);  //  I CAN SEE THE TOKEN
}

1 个答案:

答案 0 :(得分:1)

您需要在回调中使用箭头函数,因为当您使用函数语法声明一个时,此是指函数的上下文:

@Injectable()
export class AuthService {
public globalToken: string;

constructor(...){}

getToken() {

var request = require('request');

return request.post({
  uri: "https://api.sandbox.paypal.com/v1/oauth2/token",
  headers: {
    "Accept": "application/json",
    "Accept-Language": "en_US",
    "content-type": "application/json"
  },
  auth: {
    'user': 'xxxxxxx',
    'pass': 'xxxxxxx',
    // 'sendImmediately': false
  },
  form: {
    "grant_type": "client_credentials"
  }
},(error, response, body) => {
  let json = JSON.parse(body);
  // console.log('token', JSON.stringify(json.access_token));
  this.globalToken = json.access_token;
  console.log('tokentoken', this.globalToken);
});

}