Учитывая, что 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 из . Затем последующее присвоение токена и возврат запроса post могут быть обработаны внутри конвейерных операторов, таких как 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;
});