如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
How to access object properties in Angular 2 http rxjs catch function with (this)
使用angular 2中的新http服务,我想对我的错误做更多的处理,而不仅仅是在控制台中抛出错误。不幸的是,我似乎无法从catch回调函数中访问我的对象属性。
我的http服务呼叫:
return this.http.get(this.apiUrl, options)
.map(this.extractData, this)
.catch(this.handleError)
我的句柄错误回调fn:
handleError (error) {
console.log(this)//undefined!
if(error.status === 401){
this.router.navigate(['/login'])//because `this` is undefined, this does not work
}
...
}
根据rxjs-docs的说法,catch不支持第二个thisArg
参数,这在map函数中非常有用:
extractData(res) {
console.log(this)//returns the instance of my service class, which is what I want
this.someFunctionInMyService()//works great! In fact, I could call this.router.navigate if I wanted.
return res.json()
}
那么,我如何从handleError
回调中调用或使用我的服务的属性呢?
您的问题是直接引用函数,因此在执行时会丢失其上下文(this
)。
为了防止这种情况,你需要包装你的方法:
return this.http.get(this.apiUrl, options)
.map(this.extractData, this)
.catch(err => {
this.handleError(err);
})
或者利用bind
方法:
return this.http.get(this.apiUrl, options)
.map(this.extractData, this)
.catch(this.handleError.bind(this)
但是在TypeScript中使用第二种方法也有缺点,因为您会丢失类型。
请参阅此链接:
- https://basarat.gitbooks.io/typescript/content/docs/tips/bind.html
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 将函数的上下文应用于javascript变量
- 如何在JavaScript中将字符串转换为函数引用
- 用嵌套函数和默认函数定义函数
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- 无法导出函数expressjs/requestjs中的变量
- 函数参数中的数据与指定变量之间的任何性能差异
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- bluebird promise catch() 没有使用 Promise.CancelError 调用内部函数
- 有没有一种方法可以将try-catch添加到Javascript中的每个函数中
- 当使用函数引用时,Coffeescapet会奇怪地转换try/catch/finally块
- 封装Javascript中Try-Catch块中的函数
- JavaScript:作为参数传递的Try/Catch vs error函数
- 有没有一种方法可以在函数中注入try catch ?
- 用于检查javascript中是否存在函数的try/catch替代方案
- 为什么bluebird promise内部的async函数抛出的错误没有被.catch()函数捕获?
- 两个并行运行的异步函数都完成执行的Catch时刻
- 在Node.JS中尝试catch-in函数
- 如何使用编码模式/框架在try-catch块中执行每个Javascript函数(或范围内的函数)
- 从*class*构造函数发出的Catch事件