Angular 2 consecutive http requests

920 views Asked by At

In my angular data service I am trying to make two http request, with the second request depending on data from the first request. The first request is working fine, but for some reason the second request is never hitting my backend server. I was hoping if someone can tell me if I am doing this correctly or show me what I am doing wrong.

@Injectable()
export class DataService {

  constructor( private http: Http ) { }

public twoRequest() {
    this.http.get(`http://localhost:3000/1st_request`).subscribe((data) => 
      this.http.post(`http://localhost:3000/2nd_request`, {data: data}))
}

edit: I didn't subscribe to the second request. I didn't know you have to subscribe to each request you make even if they are in the same block of code

2

There are 2 answers

0
Suren Srapyan On BEST ANSWER

You need to subscribe to the http.post also. It will never do a request if you don't subscribe to it.

@Injectable()
export class DataService {

  constructor( private http: Http ) { }

  public twoRequest() {
     this.http.get(`http://localhost:3000/1st_request`).subscribe((data) => 
       this.http.post(`http://localhost:3000/2nd_request`, {data: data}).subscribe(/*...*/));
}
1
Rohan Fating On
public twoRequest() {
        this.http.get(`http://localhost:3000/1st_request`).subscribe((data) => {
            this.http.post(`http://localhost:3000/2nd_request`, {data:data})) 
               .subscribe((resp: any) => {
                 console.log(resp)
             })
           }

    }