0

I want to get the model from my api.

For this I use the method:

    [HttpGet]
    public MyModel GetModel()
    {
        MyModel model = new MyModel() { ... };

        return model;
    }

How can I get the model result in angular and how do I map MyModel to my angular model?

I have the following:

getModel() {
    var url = '/MyController/GetModel/';
    this.http.get(url)
        .map((data: Response) => {
            return data.json() as MyModel;
        })
        .toPromise().then(x => {
            this.myModel = x;
        })
}

which I call in ngOnInit of my component.

But I'm getting an error:

Uncaught (in promise): SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

What's wrong with my angular request?

nickornotto
  • 1,946
  • 4
  • 36
  • 68
  • please check if your response is a valid json - [jsonlint](https://jsonlint.com/). – Avinash Jun 26 '18 at 15:28
  • which version of Angular you are using? if its 4.3+ and you are using HttpClient then you are using older approach in your code examples. – Sergey Rudenko Jun 26 '18 at 15:28
  • It's Angular 5 and I'm using `Http` @Sergey – nickornotto Jun 26 '18 at 15:29
  • this link should help you https://stackoverflow.com/questions/22875636/how-do-i-cast-a-json-object-to-a-typescript-class – Maxim Kasyanov Jun 26 '18 at 15:30
  • @Avinash I was returning the object not the json as per my code above. I changed the method to return json eg. `public JsonResult GetModel() { MyModel myModel = new MyModel() {..}; var result = JsonConvert.SerializeObject(myModel); return Json(result, JsonRequestBehavior.AllowGet); }` but now angular request doesn't even hit the action – nickornotto Jun 26 '18 at 15:35

2 Answers2

0

the http.get takes a generic so you can do this.

  getModel() {
        var url = '/MyController/GetModel/';
        this.http.get<MyModel>(url).toPromise().then(x => {
                this.myModel = x;
        });
    }

unless the model in your angular is diferent from the model from the api

Obed Amoasi
  • 1,837
  • 19
  • 27
0

I got it working like this:

getModel() {
    var url = '/MyController/GetModel/';
    return this.http.get(url)
        .map((data: Response) => {
            return data.json();
        }).toPromise().then(x => {
            this.myModel = new MyModel(x);
        })
}

MyModel has to have a constructor accepting json string.

nickornotto
  • 1,946
  • 4
  • 36
  • 68