我正在尝试使用 Angular HttpClient 调用获取一些数据并在成功时返回一些内容,如下所示:
return this.http.post('api/my-route', model).subscribe(
data => (
this.data = data;
return $window.location = ReturnUrlService.getAbsolute('/my-other-route');
)
)
为什么我不能这样做?我的应用程序是 Angular 4.3 和 TypeScript 2.6.2 我的理解是箭头函数应该相当于这个回调:
function(data) {
this.data = data;
return $window.location = ReturnUrlService.getAbsolute('/my-other-route');
}
...我将“数据”视为 JQuery AJAX 中的“成功”回调。订阅是否在某种程度上仅限于设置类内属性的值?我的箭头函数出了什么问题?我知道我错过了一些基本的东西!
最佳答案
如果“主体”是表达式,则只能使用 ()
。你的“ body ”有两个陈述:
return this.http.post('api/my-route', model).subscribe(
data => (
this.data = data;
return $window.location = ReturnUrlService.getAbsolute('/my-other-route');
)
)
应该是:
return this.http.post('api/my-route', model).subscribe(
data => { // <==== changed this line
this.data = data;
return $window.location = ReturnUrlService.getAbsolute('/my-other-route');
} // <==== changed this line
)
return
语句
看来您只是想执行分配,而不是返回任何值。如果是这种情况,只需从最后一条语句中删除 return
关键字即可。
另一方面,如果您确实还想将该值返回给该函数的调用者,则不要使用 subscribe
,但其他函数只会转换 Observable
,such as map
:
public myMethod(): Observable<any> {
// ... create the model variable
return this.http.post('api/my-route', model).map(
data => {
this.data = data;
return $window.location = ReturnUrlService.getAbsolute('/my-other-route');
}
)
}
当然,请记住无论您在哪里调用myMethod
,都要订阅结果:
public someOtherMethod() {
return this.myMethod().subscribe(stuff => console.log(stuff));
}
关于javascript - Angular 与 TypeScript - 如何在可观察回调中处理业务逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49020929/