我已经尝试了很多天通过 stackoverflow 修复此错误,因为我现在是 Angular 的新手,所以我只需要向社区询问。我一直在研究 JWT 身份验证
ERROR TypeError: Cannot read property 'subscribe' of undefined at RawMaterialComponent.loadRawMaterialsByCompany (raw-material.component.ts:774)
我在组件中有一个如下的服务调用
private loadRawMaterialsByCompany(callback: any) {
let serviceSubscriptions =this.rawMaterialService.getRawMaterialsByCompany().subscribe(data => {
this.rawMaterials = data;
this.rawMaterialLoading = false;
},
error => this.handleError(error));
}
服务如下
getRawMaterialsByCompany() {
const url = this.raw_material_api_endpoint + 'Company/' + this.company_id;
return this.get(url);
}
以上服务调用重定向到基础服务,它实现了所有 http 请求,即: get 、 post
我在这里想做的是,如果访问 token 已过期,我想刷新 token 。使用post请求
protected get(url: string) {
if (this.isTokenExpired(localStorage.getItem('userToken'))) {
this.getOriginalDataset(url).then((val)=>{
this.getTokenfromService()
return(val)
});
} else {
return this.http.get(url)
.map(this.extractRequests)
.catch(this.handleError);
}
protected post(url: string, body: any) {
if (url.includes("RefreshToken") || url.includes("Login") || url.includes("Logout")) {
return this.http.post(url, body, { headers: this.getHeaders() })
.map(this.extractRequests)
.catch(this.handleError);
}
else {
return this.http.post(url, body, { headers: this.getHeaders() })
.map(this.extractRequests)
.catch(this.handleError);
}
}
**现在我不会刷新帖子请求的 token
getOriginalDataset() 方法获取原 Material 组件请求的数据
getTokenfromService() 方法获取新的访问 token 和刷新 token 以存储在本地存储中
sendoriginalDataset(originalUrl):Promise<any>{
return new Promise(resolve => {
const dataSet= this.http.get(originalUrl, { headers: this.getHeaders() })
.map(this.extractRequests)
.catch(this.handleError);
resolve(dataSet)
});
}
async getTokenfromService() {
const base64EncodedJwtAndRefreshToken = btoa(encodeURI(`${localStorage.getItem('userToken')}:${localStorage.getItem('refreshToken')}`));
const url = this.login_api_endpoints + 'RefreshToken/';
this.asyncResult = await this.post(url, JSON.stringify(base64EncodedJwtAndRefreshToken))
.toPromise();
console.log('First Promise resolved.')
if (this.asyncResult !== null) {
localStorage.setItem('userToken', this.asyncResult.jwtToken)
localStorage.setItem('refreshToken', this.asyncResult.refreshToken)
}
}
两种方法都运行正常,但是一旦 getTokenfromService() 执行 post 请求,控制台就会弹出错误 无法读取未定义的属性“订阅”
每个 http 请求都会发生这种情况,上面是一个示例。非常感谢您的小帮助!
最佳答案
您无法订阅
Promise。变化:
this.getOriginalDataset(url).then((val)=>{
this.getTokenfromService()
return(val)
致:
return from(this.getOriginalDataset(url)).pipe(
tap(() => this.getTokenfromService())
)
关于node.js - Angular 5 : Cannot read property 'subscribe' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56304225/