鉴于storage.get()
是异步的,您应该在then
块中处理后续操作。这将防止token
成为undefined
的问题,因为您将需要等待storage.get()
的承诺被退回。
sendPostRequest() {
var token: string;
this.storage.get('ACCESS_TOKEN').then((val) => {
token = val;
const headers = new HttpHeaders()
.set('Accept','application/json')
.set('Content-Type','application/json')
.set('Authorization','Bearer ' + token)
.set('responseType','text');
let postData = this.signatureForm.value;
this.httpClient.post("http://localhost:3000/signature",postData,{ headers: headers })
.subscribe(data => {
this.presentToast();
},error => {
this.showError = true;
this.errorMessage = error.error.message
});
});
}
但是,如果要使用Angular / RxJS方式进行操作,则可以使用RxJS from运算符将promise转换为可观察的。然后,可以在诸如switchMap之类的可管道运算符中处理令牌的后续分配和发布请求的返回。
from(this.storage.get('ACCESS_TOKEN'))
.pipe(
switchMap((val) => {
token = val;
// do the rest here
// return this.httpClient.post()
}),).subscribe(data => {
this.presentToast();
},error => {
this.showError = true;
this.errorMessage = error.error.message;
});
,
您必须在您的诺言的成功回调中实现逻辑,如下所示:
sendPostRequest() {
var token: string;
this.storage.get('ACCESS_TOKEN').then((val) => {
this.postSignature(val);
});
}
private postSignature(token: string) {
const headers = new HttpHeaders()
.set('Accept','application/json')
.set('Content-Type','application/json')
.set('Authorization','Bearer ' + token)
.set('responseType','text');
let postData = this.signatureForm.value;
this.httpClient.post("http://localhost:3000/signature",{ headers: headers })
.subscribe(data => {
this.presentToast();
},error => {
this.showError = true;
this.errorMessage = error.error.message
});
}
Promise是异步的,这意味着在完成请求之前您没有令牌值,这就是为什么您需要在成功回调中实现逻辑。
本文链接:https://www.f2er.com/3157771.html