6
2番の角度で新しいhttpサービスを使用すると、コンソールにエラーを投げるだけでなく、私のエラーでさらにやりたいと思います。残念ながら、キャッチコールバック関数内からオブジェクトプロパティにアクセスできないようです。Angular 2のオブジェクトプロパティにアクセスする方法(this)
マイHTTPサービスの呼び出し:
return this.http.get(this.apiUrl, options)
.map(this.extractData, this)
.catch(this.handleError)
マイ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のドキュメントによると、漁獲量は、マップに非常に有用である二thisArg
引数をサポートしていません。機能:
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
コールバック内から
恐ろしい:
は、このリンクを参照してください!関数のコンテキストの私の理解の欠如。 ...また、私は前に関数でラップしようとしましたが、矢印関数ではなく、私は矢印関数の本当の目的を忘れていました。ありがとう! – Joao
ありがとう!完璧に働いた。 – michali