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