2
votes

I'm using Angular 6.

I'm calling the service(service2) getData from another service(service 1). The post request is successful in the service2 and prints out the data to the console. However, the data is not returned to service1 which is calling service2 and 'result' object is always undefined.

Calling service (service1)

this.service.getData(id, token).then(
  result => {
    console.log("result " + result);
  },
  error => {
    console.log("error " + error);
  });

Service (service2)

getData(id, token): Promise < any > {
  var startTime: number = new Date().getTime();

  return new Promise < any > ((resolve, reject) => {
    this.http.post(url, soapMessage, {
      headers: new HttpHeaders().set('Content-Type', 'text/xml'),
      responseType: 'text'
    }).toPromise().then(
      res => { // Success
        resolve();
        console.log(res);
        //return res;
      },
      msg => { // Error

      }
    );
  });
}
2
You fulfill the promise with an empty object. Pass the res object to the resolve method. - Shane

2 Answers

2
votes

You missed to pass the res in resolve:

.then(res => { // Success
      resolve(res);
      console.log(res);
      //return res;
    },

NOTE:

Not really sure why you're returning a Promise for no reason at all. You code can be significantly refactored like this:

Service 2:

getData(id, token): Promise < any > {
  var startTime: number = new Date().getTime();

  return this.http.post(url, soapMessage, {
    headers: new HttpHeaders().set('Content-Type', 'text/xml'),
    responseType: 'text'
  });
}

Service 1:

this.service.getData(id, token).subscribe(
  result => {
    console.log("result " + result);
  },
  error => {
    console.log("error " + error);
  });
0
votes

Better use rxjs observable.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Observable} from 'rxjs';
import {Idata} from './Idata'
@Injectable()
export class ShareService {

    constructor(private httpc:HttpClient)
    {
    }

    public getPosts():Observable<Idata[]>
    {
        return this.httpc.get<Idata[]>('https://jsonplaceholder.typicode.com/posts');
    }
}

//In your component subscribe to Observable<Idata[]> to get instance of Idata


  public data:Array<Idata>=[];
  constructor(public service:ShareService)
  {
     this.service.getPosts().subscribe(value => {
        this.data=value;
     });
  }

Executable online demo