0

I have a provider class having a request function. It works fine:

sendRequest(requestBody:any,URL:string){
    let headers = new Headers();
    headers.append("Accept", 'application/json');
    headers.append('Content-Type', 'application/json' );
    let options = new RequestOptions({ headers: headers });

    let body=requestBody;
    body.key=this.key;

    this.http.post(this.url+URL, body, options)
      .subscribe(data => {
        let json=JSON.parse(data['_body']);

          let toast=this.toast.create({
            message:json.response,
            duration:3000,
            position:'top'
          });
          toast.present();
          return json;
      }, error => {
        console.log(error);// Error getting the data
      });
  }

I want to call this method and want json response in another class. I tried calling in promise but didn't worked out. Any help would be highly appreciated.

Edit: I want to perform toast as well as I tried returning this.http.post... it is returning a subscribe object. How can I fetch json data from that?

**Edit # 2 ** I successfully returned the data using map on definition and subscribe on call side.

return this.http.post(this.url+URL, body, options)
      .map((data) => {
        let json=JSON.parse(data['_body']);

          let toast=this.toast.create({
            message:json.response,
            duration:3000,
            position:'top'
          });
          toast.present();
          return json;
      }

and called using

this.request.sendRequest(requestBody,'api/login').subscribe((data)=>{
      console.log(data);
    });

Toast works too.

Solved

3
  • 2
    you have to return it: return this.http.post ... then you can call it from another method Commented Apr 26, 2018 at 13:06
  • Check this thread link Commented Apr 26, 2018 at 13:08
  • Possible duplicate of Angular2 handling http response Commented Apr 26, 2018 at 13:10

1 Answer 1

0

If your goal is to append headers and display a toatser, consider using an interceptor from the new Http Client module :

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

  let headers = new Headers();
  headers.append("Accept", 'application/json');
  headers.append('Content-Type', 'application/json' );
  let options = new RequestOptions({ headers: headers });

  const clone = req.clone({ setHeaders: headers });

  return next
    .handle(clone || req)
    .map(response => {
      this.toast.create(...);
      return response;
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.