【发布时间】:2019-10-11 17:45:55
【问题描述】:
我已经尝试了很多天来解决 stackoverflow 上的这个错误,因为我现在是 Angular 的新手,所以我只需要向社区询问。我一直在研究 JWT 身份验证
错误类型错误:无法读取未定义的属性“订阅” 在 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
我在这里要做的是,如果访问令牌已过期,我想刷新令牌。使用发布请求
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);
}
}
**现在我不会为发布请求刷新令牌
getOriginalDataset() 方法为原材料组件带来请求的数据
getTokenfromService() 方法获取新的访问令牌和刷新令牌存储在本地存储中
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() 执行发布请求,控制台错误就会弹出 Cannot read property 'subscribe' of undefined
每个 http 请求都会发生这种情况,上面是一个示例。非常感谢您的小帮助!
【问题讨论】:
标签: node.js angular typescript ecmascript-6 rxjs