How to make a synchronous call in angular 5?

后端 未结 5 1232
我寻月下人不归
我寻月下人不归 2021-01-11 11:33

So, I was trying to get the solution of this problem. But, somehow I am unable to do so, May be because of the lack of knowledge in angular 5. This is my service:

         


        
5条回答
  •  甜味超标
    2021-01-11 12:33

    there is no direct way to make a synchronous call, however you can do the following procedure (this code is written in angular 7).

    import { Component, OnInit } from '@angular/core';
    import {HttpClient} from '@angular/common/http';
    
    export class SampleComponent implements OnInit {
      Request1result:Object;
      Request2result:Object;
    
      constructor(private http:HttpClient) { }
    
       ngOnInit() 
       {
        this.http.get("URL1").subscribe((res)=>{
          this.Request1result=res;
          this.after1(); // execution will move to next request only when first is done.
        });
       }
      after1()
      {
        this.http.get("URL2").subscribe((res)=>{
          this.Request2result=res;
          this.after2(); // execution will move to the rest of the code only when both the requests are done.
        });
      }
      after2()
        {
        // rest of the code.
        console.log(this.Request1result);
        console.log(this.Request2result);
    
        }
    
    }

提交回复
热议问题