1

I have simple method in aspnet web api with following test results:

$ curl localhost:5000/Api/GetAllQuestions 
[{"questionId":0,"value":"qqq","answers":[{"answerId":25,"value":"qwerty"}]}]

In angular2 http service something is wrong:

GetQuestions(): Observable<Question[]> {
    return this.http.get("Api/GetAllQuestions")
        .map(this.extractData)
        .catch(this.handleError);
}

private extractData(res: Response) {
    let body = res.json();
    console.log(res.json()[0]);
    return body.data || {};
}

because it returns {} every time, but in console log I have some expected results:

 Object { questionId: 0, value: "qqq", answers: Array[1] }

What am I doing wrong, and how can I parse JSON successfully?

1
  • You're asking it to return body.data or {}... i don't think data exists on body, what happens if you just return body? Commented Jul 6, 2016 at 18:05

2 Answers 2

2

You have a problem in your extractData method. The res.json method returns the payload of the response:

private extractData(res: Response) {
  let body = res.json();
  return body || {}; // <------
}

You can return body.data if you have a response payload like this:

{
  data: [
    {
      "questionId":0,"value":"qqq","answers": [
        {"answerId":25,"value":"qwerty"}
      ]
    }
  ]
}
Sign up to request clarification or add additional context in comments.

Comments

1

I assume you're using as reference the angular documentation. Am I right?

What happens is that body.data expects that the Http response contains such property. So if your api returns an object with different it's not going to work.

Look at what is written in angular docs, right bellow where you took the snippet from:

Make no assumptions about the server API. Not all servers return an object with a data property.

So this is pretty much the reason why .data is undefined.

2 Comments

maybe you know, some guide to integrate dotnet web api and angular?
Either way the answer is still the same. The object returned from the api must have .data property. Log the body on the console and check the structure. Then will find the answer.

Your Answer

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