Search code examples
angularweb-serviceshttpasynchronousangular-httpclient

return array is undefined in angular 4


I'm getting data from web service and trying to use toPromise in my service.web service returns below json object.

[
  {
    "username": "jack",
    "joinDate": "2017-10-28T00:00:00",
    "expireDate": "2017-10-31T00:00:00",
    "isActive": true,
    "userurl": "https://dummy.com",
    "masterkey": "77uyerue987930000",
    "appkey": "hdhfjd98984300000",
    "id": 49
  },
  {
    "username": "paul",
    "joinDate": "2017-10-28T00:00:00",
    "expireDate": "2017-10-31T00:00:00",
    "isActive": true,
    "userurl": "https://dummy.com",
    "masterkey": "98dfdf88",
    "appkey": "89fdf98",
    "id": 49
  }
]

then here is my method to consume response from web service :

returntestData() {


const url:string = 'https://userportal/api/company';
this.nhttp.get(url)
      .toPromise()
      .then(res => <Users[]> res.json().data)
      .then(
        data => {
          console.log(data)
          return data
        }
      );
  }

so the data is always undefined. then I cannot use it in my component.

in other hand I tried below

getallCompanies(): Users[] {

let UsersDetails: Users[] = [];

const url:string = 'https://userportal/api/company';

this.http.get<[{Users}]>(url).subscribe(
  data => {
     for(var i=0;i<data.length;i++) {
      let newuser = new Companies(data[i]["username"],data[i]["id"],data[i]["isActive"],data[i]["joinDate"],data[i]["expireDate"],data[i]["appkey"],data[i]["masterkey"],data[i]["userurl"]);
      UsersDetails.push(newuser);
     }
     console.log("full data from service : "+ UsersDetails);
     return UsersDetails;

  },
  err => {
    console.log("error occured while calling to web service");
    console.log(err)
  }
);

return UsersDetails;


 }

above code returns the values correctly. but it returns the value after view loaded.not a async call. hope your help with this.


Solution

  • If you use the new HttpClient, there is no res.json method. It will work automatically, just pass the response type like this:

    returntestData() {
        const url:string = 'https://userportal/api/company';
    
        return this.http.get<Users[]>(url)
            .toPromise()
            .then(data => {
                console.log(data)
                return data
            });
    }
    

    It also depends on the interface Users.