读取全局变量 Ionic



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

@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"时,返回"未定义"。

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

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

@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);
});
}

最新更新