[英]Angular 2 http - send request conditionally
您好,我需要处理HTTP。 我需要使用条件发送请求,这里是示例:
我需要发送POST /api/files
但发送是基于服务器api的条件: GET /api/condition
返回true或false。 如果返回true,则可以调用/api/files
,如果为false,则需要调用POST /api/enable.
1。 GET / api / condition
1个 返回true-> 2。
1羽 返回false-> 3。
2。 POST / api /文件
3。 POST / api /启用-> 1。
最简单的方法如下:
load(){
http.get(/api/condition).subscribe(response => {
if(response == true)
http.post(/api/files).subscribe()
else http.post(/api/enable).subscribe(x => this.load())
})
}
但这尚不清楚解决方案。 用什么方法可以创建这个? 谢谢
post方法返回一个可观察到的冷信号,因此需要调用subscription才能执行。 因此,您拥有的是最简单的方法。 您可以进行一些小的重构,但是核心原理将保持不变
好的,您使代码正常工作,您唯一能做的就是模块化整个模块并将其拆分为适当的功能。
检查条件要求
fetchCondition(): Observable<boolean> {
return http.get(/api/files).map((response: boolean) => response);
}
提取文件
fetchFiles(): Observable<YourFile[]> {
return http.post(/api/files).map((response: YourFile[]) => response);
}
启用文件提取
enable(): Observable<any> {
http.post(/api/enable).map((response: any) => response);
}
逻辑-拼凑而成
load(){
this.fetchCondition().subscribe(
condition => {
if(condition) {
this.fetchFiles().subscribe(
files => this.doSomethingWithFiles(files),
err => { /* handle */ }
);
} else {
this.enable().subscribe(resp => this.load());
}
},
err => { /* handle */ }
);
}
请注意,您可以进入无限循环! 如果服务器以某种方式无法启用您正在检查的条件,则运行load函数可能会使您陷入无限循环。 我建议使用某种计数器/调度程序来解决这种漏洞。 当然,这完全取决于应用程序的上下文和复杂性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.