0

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.

2
  • Are you using new HttpClient as you tagged this question? There is no res.json() method there, it converts json automatically. Commented Oct 30, 2017 at 12:43
  • Also you have a typo there this.nhttp instead of this.http I guess. Commented Oct 30, 2017 at 12:44

1 Answer 1

1

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.

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.