Angular 2 http - 有条件地发送请求

Angular 2 http - send request conditionally

您好,我需要处理 HTTP。我需要使用这里的条件发送请求是示例:

我需要发送 POST /api/files - 但发送在服务器上是有条件的 api: GET /api/condition - return 对或错。如果 return 为真,则可以调用 /api/files,当为假时,我需要调用 POST /api/enable.

1。获取 /api/condition

1个return 正确 -> 2.

1 return 错误 -> 3.

2。 POST/api/files

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())
  })
 }

但目前还没有明确的解决方案。有什么方法可以创建它吗?谢谢

post 方法 returns 是一个冷可观察对象,因此需要调用订阅才能执行。所以你拥有的是最简单的方法。您可以进行一些小的重构,但核心原则将保持不变

好吧,您的代码可以正常工作了,您唯一能做的就是将整个块模块化并将其拆分为适当的功能。

检查条件请求

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 */ }
   );
}

请注意,您可能会进入无限循环! 运行 如果您的服务器以某种方式无法启用您在函数开始时正在检查的条件,则加载函数可能会使您陷入无限循环。 我会推荐某种可以解决这种漏洞的计数器/调度程序。当然,这完全取决于您的应用程序的上下文和复杂性。