Passing the response of http post1 to another and getting response back from post2 in Angular

Viewed 45

I'm trying to post a request for authorizing a user. After logging in I want to send another http.post to set some information about that user. So far my login call works : (Angular) auth_service.ts :


Login() {
    let promiseResult : any;
    this.http.post<any>('/auth/Login', this.auth_payload).toPromise().then(data => {
      promiseResult = data;
      console.log("Login call" ,promiseResult)
      return promiseResult

    });

auth_component.ts :

 onSubmit(form : NgForm){
    this.authService.Login()
  }

I'm having trouble understanding how to make the second post request work. I want to press a button on the HTML upon which the response from the second call will be retrieved. How should I make a "connection" between these two requests?

I've read about Promises and Observables but I don't get how do I use them in this case.

3 Answers
YourMethod(): Observable < any > {
  let firstResult;
  let secondResult;

  return http.get('////').pipe(
    switchMap(res1 =>  this.http.post<any>('/auth/Login', this.auth_payload).pipe(
      map(res2 => [res1, res2])
    ))
  );
}

CallingMethod() {
  this.YourMethod().subscribe(([firstResult, secondResult]) => {
    /// Some logic
  })
}

Add a call to your second endpoint in your promise callback:

Login() {
    let promiseResult : any;
    this.http.post<any>('/auth/Login', this.auth_payload).toPromise().then(data => 
    {
      promiseResult = data;
      console.log("Login call" ,promiseResult)
      this.setInformation(data)
      return promiseResult

    });

setInformation(userData) {
    let promiseResult : any;
    this.http.post<any>('/information/endPoint', userData).toPromise().then(data => {
      promiseResult = data;
      console.log("set Information call" ,promiseResult)
      return promiseResult

    });

However I am not sure that this is conceptually correct if the login and the set information are on the same server you can manage this directly in your server application

Whatever your return from a then is going to be passed to the next one, so you can just do that:

this.http.post<any>('/auth/Login', this.auth_payload)
    .toPromise()
    .then(data => this.doSomethingMore(data))
    .then(moreData => this.doSomethingElse(moreData));

You can shorten .then(data => this.doSomethingMore(data)) with .then(this.doSomethingMore) but for clarity sake, I didn't do it.

If doSomethingMore return a Promise then it will be executed and its result passed to the next then.

Same with Observable:

this.http.post<any>('/auth/Login', this.auth_payload)
    .pipe(
        switchMap(data => this.doSomethingMore(data)),
        switchMap(moreData => this.doSomethingElse(moreData)),
    );
Related