这与redirect to a route after api call in angular2类似,但我想使用类变量(this.areaCode
)作为重定向的一部分或更新变量(this.userInfoMessage
)。例如:
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}`]); // eg: "/areas/12" //"this" is of type SafeSubscriber, not my class
}
private handleError (error: any) {
this.userInfoMessage="We've got errors here!" //"this" is of type SafeSubscriber, not my class so the message is now bound
console.log(error)
}
但是我无法理解如何在这些函数中获取对类的引用。我是否需要使用self=this
技巧。如果是这样,怎么样?
由于
更新
我尝试将this
传递给this.taskService.createTask(task).subscribe(this.taskCreated,this.handleError).bind(this)
但Property 'bind' does not exist on type 'Subscription'.
更新(2)
我想问题是"如何将引用传递给订阅回调?"
如果我想订阅传入对当前对象的引用,我已经尝试过使用
读取链接的Qvar self= this
this.taskService.createTask(task).subscribe(this.taskCreated(self),this.handleError)
它无法编译。 我仍然将回调定义为 private taskCreated(resp:any)
我不认为这与链接的Q完全相同。
我错过了什么?
由于
答案 0 :(得分:2)
你可以试试这个:
CTCallCenter *callCenter = [[CTCallCenter alloc] init];
callCenter.callEventHandler = ^(CTCall* call) {
//Native call changes are triggered here
};
答案 1 :(得分:2)
您需要bind
这些函数本身,而不是Subscription
方法返回的subscribe
。
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文档尽可能建议不要使用函数绑定,所以我会使用后两种解决方案之一。