你好,我需要处理 HTTP。我需要使用条件发送请求,这里是示例:
我需要发送POST/api/files
- 但发送是有条件的服务器API:
GET/api/condition
- 返回 true 或 false。如果返回true,则可以调用/api/files
,如果返回false,我需要调用POST/api/enable。
1.获取/api/条件
1a。返回 true -> 2。
1 b.返回 false -> 3。
2. POST/api/文件
3. POST/api/enable -> 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())
})
}
但这不是明确的解决方案。有什么方法可以创建这个吗?谢谢
最佳答案
好吧,你已经让代码正常工作了,你唯一能做的就是模块化整个 block 并将其拆分为适当的函数。
检查条件请求
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 */ }
);
}
请注意,您可能会进入无限循环! 如果您的服务器以某种方式无法启用您在函数开始时检查的条件,则运行加载函数可能会让您陷入无限循环。 我会推荐某种计数器/调度程序来处理这种漏洞。当然,这完全取决于应用程序的上下文和复杂性。
关于Angular 2 http - 有条件地发送请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47772970/