将您的可观察响应转换为承诺,可以轻松地从您需要的地方进行呼叫。
const getUserLogged = () => { const tkn = await this.authService.getToken(); return this.http .post('http://localhost:8000/api/getuser/', { token: tkn }) .toPromise(); }; const someOtherFunc = async () => { const user = await getUserLogged(); console.log({ user }); };
以下是我将如何设置此方法:
getUserLogged() { return this.authService.getToken().pipe( switchMap(tkn=> { return this.http.post('http://localhost:8000/api/getuser/', { token: tkn }) }) ); }
然后使用此方法如下:
getUserLogged().subscribe(userData => console.log(userData));
这种方法使用了 switchMap 只调用的运算符 http.post 一旦 authService.getToken 返回令牌。您可以找到所有RxJs运算符的文档 这里 。
http.post
authService.getToken