加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

api – angular2中的同步GET请求

发布时间:2020-12-17 17:09:05 所属栏目:安全 来源:网络整理
导读:我想在Angular2中创建一个组件,其中将执行50次迭代的循环,并且我只想在偶数迭代中发送GET请求.现在我想发送同步GET请求,除非直到没有收到来自偶数迭代的数据,否则循环应该等待而不是进入奇数迭代.关于如何做到这一点的任何想法? 这是服务中写的函数 – ` ge
我想在Angular2中创建一个组件,其中将执行50次迭代的循环,并且我只想在偶数迭代中发送GET请求.现在我想发送同步GET请求,除非直到没有收到来自偶数迭代的数据,否则循环应该等待而不是进入奇数迭代.关于如何做到这一点的任何想法?

这是服务中写的函数 – `

getUser() {
     for(let i = 1;i < 10;i++) {
      if (i % 2 != 0) {         
      var resp =this.http.get('https://jsonplaceholder.typicode.com/users/'+i)
          .map(res=> res.json());

      if(resp){
      resp.subscribe(res=>{
        console.log(res);
      });
    }

  }
  else{
    console.log("even iteration");
  }
}

这是输出 –

And here's the output -

我希望问题现在很清楚.响应应该按顺序排列,并且只有当奇数对应物返回对象时才应显示偶数迭代控制台消息.请提出解决方案.

解决方法

所以在我的教师的帮助下,我们终于实现了我们想要的.我们发送异步请求并将响应作为可观察对象返回.现在我们连接这些可观察对象,在交替循环迭代时返回并实现以下输出-

output

这是我的代码 –

service.ts –

getUser(i: number): Observable<any>{
  return this.http.get('https://jsonplaceholder.typicode.com/users/' + i)
    .map(res => res.json());

 }

component.ts –

import {Component,OnInit} from '@angular/core';
import {AppService} from "./app.service";
import {Observable} from 'rxjs/Rx';

 @Component({
 selector: 'app',templateUrl: './app.component.html'
 })
 export class AppComponent implements OnInit {


  name:string;
  call: Observable<any>;

   constructor(private _service: AppService) {}

    public ngOnInit() {

   }

  getUser(){
    this.call = Observable.concat();
   for(let i=1;i<=10;i++) {
     if(i%2!=0){
       this.call = this.call.concat(this._service.getUser(i));
      }
     else{
       this.call = this.call.concat(Observable.create(x=> {x.next(i)}).first());
      }
    }
        this.call.subscribe(res=>console.log(res));

    }
  }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读