这是我的 Http 请求 在 getAllUserData() 中,我希望 this.getAnXSRfToken() 在继续 http 请求之前完成 exe;
getAllUserData() {
//get XSRF token
this.getAnXSRfToken();
return this.http
.post<User[]>('http://localhost:8080/user/get-all-users-post', null, {
observe: 'response',
withCredentials: true,
})
.subscribe({
next: (array) => {
this.allUsersData.next(array.body);
},
error: (e) => {
console.log(e);
},
});
}
这里是 this.getAnXSRfToken() 方法
getAnXSRfToken() {
return this.http
.post<{
parameterName: string;
headerName: string;
token: string;
}>('http://localhost:8080/user/getXSRfToken', null)
.subscribe({
next: (tokenData) => {
console.log('REQ --- token ---generated ');
console.log(tokenData.token);
this.XSRF_TOKEN.next(tokenData.token);
},
error: (e) => console.log(e),
});
}
switchMap
从 XHR API 调用依次切换到其他 API 调用!
getAllUserData() {
//get XSRF token
this.getAnXSRfToken().pipe(
switchMap(() => {
return this.http
.post<User[]>('http://localhost:8080/user/get-all-users-post', null, {
observe: 'response',
withCredentials: true,
}).pipe(//array parameter was missed out
tap((array) => {
this.allUsersData.next(array.body);
})
)
})
).subscribe();
}
getAnXSRfToken() {
return this.http
.post<{
parameterName: string;
headerName: string;
token: string;
}>('http://localhost:8080/user/getXSRfToken', null)
.pipe(
tap((tokenData) => {
console.log('REQ --- token ---generated ');
console.log(tokenData.token);
this.XSRF_TOKEN.next(tokenData.token);
})
);
}