我正在尝试提交帖子,并发送带有标题的令牌。但是,我的storage.get返回了一个promise,而且我不知道如何从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
});
}
答案 0 :(得分:2)
鉴于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;
});
答案 1 :(得分:1)
您必须在您的诺言的成功回调中实现逻辑,如下所示:
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", postData, { headers: headers })
.subscribe(data => {
this.presentToast();
}, error => {
this.showError = true;
this.errorMessage = error.error.message
});
}
Promise是异步的,这意味着在完成请求之前您没有令牌值,这就是为什么您需要在成功回调中实现逻辑。