[英]Angular with TypeScript- how do I handle business logic within an observable callback?
我正在尝试获取一些数据并使用Angular HttpClient调用成功返回一些信息,如下所示:
return this.http.post('api/my-route', model).subscribe(
data => (
this.data = data;
return $window.location = ReturnUrlService.getAbsolute('/my-other-route');
)
)
我为什么不能这样做? 我的应用程序是带有TypeScript 2.6.2的Angular 4.3,我的理解是arrow函数应该等效于此回调:
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
函数, 例如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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.