Observable订阅返回值异常及toPromise返回undefined问题求助
问题分析与解决方案
核心错误原因
你的getHash函数返回的是subscribe()的结果——Subscription对象,而非Observable。subscribe()回调里返回的http.get Observable不会被外层函数捕获,所以调用方尝试调用.subscribe()时自然会报错“subscribe is not a function”。
至于用toPromise得到undefined,是因为你错误地在subscribe回调里使用await,此时函数返回的依然是Subscription,而非Promise,await一个Subscription无法拿到有效数据。
正确实现方式(Observable风格,推荐)
使用RxJS的switchMap操作符串联两个Observable(获取token + 发起HTTP请求),让整个函数返回一个可订阅的Observable:
import { switchMap } from 'rxjs/operators'; import { Observable } from 'rxjs'; getHash(): Observable<any> { return this.authService.getAccessTokenSilently().pipe( switchMap(jwt => { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${jwt}` }) }; const decodedToken = window.atob(jwt.split('.')[1]); const jwtoken = JSON.parse(decodedToken); const url = `${commonEnv.baseUrl}/${jwtoken.sub}/hash`; return this.http.get(url, httpOptions); }) ); }
调用示例
this.getHash().subscribe({ next: (hash) => { // 处理获取到的hash值 console.log(hash); }, error: (error) => { // 处理请求错误 console.error('获取hash失败:', error); } });
可选:Promise/await风格实现
如果更习惯Promise语法,可以将整个逻辑改为async/await:
async getHash(): Promise<any> { // 先获取token const jwt = await this.authService.getAccessTokenSilently().toPromise(); const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${jwt}` }) }; const decodedToken = window.atob(jwt.split('.')[1]); const jwtoken = JSON.parse(decodedToken); const url = `${commonEnv.baseUrl}/${jwtoken.sub}/hash`; // 发起请求并返回Promise return this.http.get(url, httpOptions).toPromise(); }
调用示例
async fetchHash() { try { const hash = await this.getHash(); console.log(hash); } catch (error) { console.error('获取hash失败:', error); } }
内容的提问来源于stack exchange,提问作者QPTR
相关产品推荐
相关产品推荐

