【问题标题】:Angular 2 http - send request conditionallyAngular 2 http - 有条件地发送请求
【发布时间】:2017-12-12 21:44:31
【问题描述】:

您好,我需要处理 HTTP。我需要使用条件发送请求,例如:

我需要发送 POST /api/files - 但发送取决于服务器 api: GET /api/condition - 返回真或假。如果返回 true,则可以调用 /api/files,如果为 false,我需要调用 POST /api/enable.

1 .获取 /api/条件

1 个。返回真 -> 2.

1 乙。返回 false -> 3.

2 。发布 /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())
  })
 }

但目前尚不清楚解决方案。有什么方法可以创建这个?谢谢

【问题讨论】:

    标签: angular angular-http


    【解决方案1】:

    好吧,你的代码工作了,你唯一能做的就是模块化整个块并将其拆分为适当的函数。

    检查条件请求

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

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

    【讨论】:

      【解决方案2】:

      post 方法返回一个冷的 observable,因此需要调用 subscribe 才能执行。所以你有的是最简单的方法。您可以进行一些小的重构,但核心原则将保持不变

      【讨论】:

        猜你喜欢
        • 2015-12-30
        • 1970-01-01
        • 2012-12-18
        • 2021-12-29
        • 1970-01-01
        • 2016-07-12
        • 1970-01-01
        • 2016-11-15
        • 2016-11-13
        相关资源
        最近更新 更多