我看了一下,但是找不到我的问题的解决方案。
情况:
我有一个DataProvider处理服务器的所有GET请求并处理错误。 发生错误时,会调用一个调用Ionic 2的AlertController的方法。
问题是我无法访问所述方法,因为它具有不同的上下文。 它可能与创建GET请求时的链接有关。
似乎bind可以解决这个问题,但我无法弄清楚如何在这种情况下实现它。
export class DataProvider { constructor(public http : Http, public alertCtrl: AlertController) { } getArticles(): Promise<any> { return this.createHttpRequestGet(this.baseUrl + 'beProduct'); } private createHttpRequestGet(url: string) : Promise<any> { return this.http.get(url, this.getRequestOptions()).map((response) => response.json()).timeout(7500).catch(this.handleError).toPromise(); } private handleError(error:any) { var message = { title: "", text: "" } switch (error.status) { case 401: // Unauthorized message.title = "..." message.text = "... (" + error.status + ")."; break; ... } // Can't access variable this this.showErrorAlertText(error.title, error.message); return Promise.reject(message); } showErrorAlertText(title: string, message: string) { this.alertCtrl.create({ title: title, subTitle: message, buttons: ['Ok'] }).present(); } }这是执行this.showErrorAlertText(..,..)之前的值
I've looked a bit around, but coudn't find a solution for my issue.
Situation:
I have a DataProvider that handles all the GET-requests to the server and handles the errors. When an error occurs, a method is called that invokes the AlertController of Ionic 2.
The problem is that I can't access said method because this has a different context. It probably has to do with the chaining when creating the GET-request.
It seems like bind can solve this problem, but I can't figure out how to implement it in this situation.
export class DataProvider { constructor(public http : Http, public alertCtrl: AlertController) { } getArticles(): Promise<any> { return this.createHttpRequestGet(this.baseUrl + 'beProduct'); } private createHttpRequestGet(url: string) : Promise<any> { return this.http.get(url, this.getRequestOptions()).map((response) => response.json()).timeout(7500).catch(this.handleError).toPromise(); } private handleError(error:any) { var message = { title: "", text: "" } switch (error.status) { case 401: // Unauthorized message.title = "..." message.text = "... (" + error.status + ")."; break; ... } // Can't access variable this this.showErrorAlertText(error.title, error.message); return Promise.reject(message); } showErrorAlertText(title: string, message: string) { this.alertCtrl.create({ title: title, subTitle: message, buttons: ['Ok'] }).present(); } }This is the value of this before executing this.showErrorAlertText(..,..)
最满意答案
选项1:
.catch(error => this.handleError(error))选项2 :(假设您使用TypeScript)
private handleError = (error:any) => { var message = { title: "", text: "" }选项3:
.catch(this.handleError.bind(this))Option 1:
.catch(error => this.handleError(error))Option 2: (Assuming you use TypeScript)
private handleError = (error:any) => { var message = { title: "", text: "" }Option 3:
.catch(this.handleError.bind(this))更多推荐
发布评论