重定向到angular中api调用后的路由(使用“this”)
这与类似,但我想使用类变量(重定向到angular中api调用后的路由(使用“this”),angular,angular-ui-router,subscribe,Angular,Angular Ui Router,Subscribe,这与类似,但我想使用类变量(This.areaCode)作为重定向或更新变量(This.userInfoMessage)的一部分。例如: 但是,我无法理解如何在这些函数中获得对类的引用。我需要使用self=this技巧吗。如果是,怎么做 谢谢 更新 我已尝试将this传递到this.taskService.createTask(task).subscribe(this.taskCreated,this.handleError).bind(this)但是属性“bind”在类型“Subscripti
This.areaCode
)作为重定向或更新变量(This.userInfoMessage
)的一部分。例如:
但是,我无法理解如何在这些函数中获得对类的引用。我需要使用self=this
技巧吗。如果是,怎么做
谢谢
更新
我已尝试将this
传递到this.taskService.createTask(task).subscribe(this.taskCreated,this.handleError).bind(this)
但是属性“bind”在类型“Subscription”上不存在。
更新(2)
我想问题是“如何将引用传递到订阅回调?”
如果我想订阅,请阅读链接Q,并传入对我尝试使用的当前对象的引用
var self= this
this.taskService.createTask(task).subscribe(this.taskCreated(self),this.handleError)
它不编译。
我仍然将回调定义为
已创建专用任务(resp:any)
我认为这和链接的Q不太一样
我错过了什么
谢谢你可以试试这个:
private handleError = (error) => {
this.userInfo = "we have a problem here";
}
您需要
bind
函数本身,而不是从subscribe
方法返回的Subscription
onSubmit(form: string): void {
this.taskService.createTask(task).subscribe(this.taskCreated.bind(this),this.handleError.bind(this))
}
另一种方法是关闭:
this.taskService.createTask(task)
.subscribe(
(res) => this.taskCreated(res),
(err) => this.handleError
)
}
在Typescript中实现这一点的一种更简洁、更清晰且鲜为人知的方法是用一个粗箭头实例化方法本身,从而生成一个始终引用类本身的词法this
:
onSubmit(form: string): void {
this.taskService.createTask(task).subscribe(this.taskCreated,this.handleError)
}
private taskCreated = (resp: any) => {
console.log("Task created successfully",resp)
this.router.navigate([`/areas/${this.areaCode}`]); // 'this' will refer to class!
}
private handleError = (error: any) => {
this.userInfoMessage="We've got errors here!" // 'this' will also refer to the class!
console.log(error)
}
官方的Typescript文档建议尽可能不使用函数绑定,因此我将使用后两种解决方案中的一种。在所有人投票结束之前,您能让我看看是否可以从另一个答案中得出我需要做的具体操作吗?
onSubmit(form: string): void {
this.taskService.createTask(task).subscribe(this.taskCreated,this.handleError)
}
private taskCreated = (resp: any) => {
console.log("Task created successfully",resp)
this.router.navigate([`/areas/${this.areaCode}`]); // 'this' will refer to class!
}
private handleError = (error: any) => {
this.userInfoMessage="We've got errors here!" // 'this' will also refer to the class!
console.log(error)
}