Search code examples
angulartypescripthttpclientangular4-httpclient

Can't return response from httpclient post function to other custom function in angular 4


I have addUser(newUser) function in sign-in.service.ts file as follows

addUser(newUser)
  {
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json' })
    };
    let body = JSON.stringify(newUser);
    this.httpclient.post('http://localhost:3000/api/signup', body, httpOptions).subscribe(res=>{
      console.log(res);
      return res;
    });
  }

Here console's output is {msg: "succesfully added", status: 200} but when i m calling the above addUser(newUser) function from sign-in.component.ts file as follows

  addUser()
  {
    console.log(this.first_name,this.last_name,this.userName,this.email);
    let newUser = {
      "first_name":this.first_name,
      "last_name":this.last_name,
      "username":this.userName,
      "email":this.email
    }
    console.log(this.signService.addUser(newUser));
  }

console output is showing undefined . Why? Please help me. Thank you.


Solution

  • httpclient is going to return you observable as per my knowledge and it logs response in subscribe method so in component you might not receive things properly as call is not completed , so you need to do like this

    addUser(newUser) : Observable<any>
      {
        const httpOptions = {
          headers: new HttpHeaders({ 'Content-Type': 'application/json' })
        };
        let body = JSON.stringify(newUser);
        return this.httpclient.post('http://localhost:3000/api/signup', body, httpOptions);
      }
    
     //make use of async/awit , so you will get response properly 
     async addUser()
      {
        console.log(this.first_name,this.last_name,this.userName,this.email);
        let newUser = {
          "first_name":this.first_name,
          "last_name":this.last_name,
          "username":this.userName,
          "email":this.email
        }
        const datareturned = await this.signService.addUser(newUser).toPromise();
        console.log(datareturned);
      }
    

    or if you dont want to go for async/await , you should surbscribe observable in your component.ts file

    addUser()
      {
        console.log(this.first_name,this.last_name,this.userName,this.email);
        let newUser = {
          "first_name":this.first_name,
          "last_name":this.last_name,
          "username":this.userName,
          "email":this.email
        }
       this.signService.addUser(newUser).subscribe(d=> console.log(d));
      }
    

    service file

    addUser(newUser) : Observable<any>
      {
        const httpOptions = {
          headers: new HttpHeaders({ 'Content-Type': 'application/json' })
        };
        let body = JSON.stringify(newUser);
        return this.httpclient.post('http://localhost:3000/api/signup', body, httpOptions);
      }