0

I'm using Angular2 with MVC 6 and I'm trying to make a call to a method on the MVC controller to return data.

My Angular service is as follows:

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';

import { ICountry } from '../interfaces/country';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';


@Injectable()
export class RecruiterService {
private _countriesUrl = 'Recruiter/Home/Countries';

constructor(private http: Http) { }

public getCountries = (): Observable<ICountry[]> =>  {
    return this.http.get(this._countriesUrl)
        .map((response: Response) => <ICountry[]> response.json())
        .do(data => console.log('All: ' + JSON.stringify(data)))
        .catch(this.handleError);
}

//public getCountries = (): Observable<{}> => {
//    return this.http.get(this._countriesUrl)
//        .map((response: Response) => <any[]>response.json())
//        .do(data => console.log('All: ' + JSON.stringify(data)))
//        .catch(this.handleError);
//}
 private handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
}
}

My ICountry interface is declared:

export interface ICountry {
CountryId: number;
CountryName: string;
ISOCode: number;
}

My MVC Controller is as follows:

[Area("Recruiter")]
[Route("Recruiter")]
[Authorize(ActiveAuthenticationSchemes = "Cookie")]
[EnableCors("AllowSpecificOrigin")]
public class HomeController : LogControllerBase<HomeController>
{ .......
   [HttpGet("/Home/Countries")]
    public IActionResult GetCountries()
    {
        try
        {
            //return new JsonResult(new object[] { 1, "England", 3 });
            return Ok(_recruiterService.GetAllCountries());
        }
        catch (Exception ex)
        {
            Logger.LogError($"Error occured in Recruiter Home/GetCountries: {ex}");
            return BadRequest("Obtaining Countries");
        }

    }......

At the point of calling the countriesUrl in my Angular service, I always receive the following error, I also get the same error when I swap out to the commented code in both the angular and mvc method. I never reach my breakpoint in the MVC controller method. I've also attempted to set the _countriesURL to be fully qualified e.g. starting http, but I still receive the same error

SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Response.Body.json (http.umd.js:777)
at MapSubscriber.http.get.map [as project] (recruiter.service.ts:20)
at MapSubscriber._next (map.ts:75)
at MapSubscriber.Subscriber.next (Subscriber.ts:95)
at XMLHttpRequest.onLoad (http.umd.js:1180)
at ZoneDelegate.invokeTask (zone.js:398)
at Object.onInvokeTask (core.umd.js:3971)
at ZoneDelegate.invokeTask (zone.js:397)
at Zone.runTask (zone.js:165)
at XMLHttpRequest.ZoneTask.invoke (zone.js:460)

In the Browser (Chrome) if I go to the network tab, I can see the call being made to the method even though it doesn't seem to breakpoint. In the headers for the call I get:

Request URL:http://localhost:42413/Recruiter/Home/Countries
Request Method:GET
Status Code:200 OK
Remote Address:[::1]:42413
Referrer Policy:no-referrer-when-downgrade

Below are network header and preview tabs Header tab Preview tab

10
  • open the browser develop tools(F12), check what the server has returned Commented Apr 20, 2017 at 6:04
  • @aspark The error shown above is the error given by the browser (chrome). From the angular line console.error(error); Commented Apr 20, 2017 at 6:06
  • the error indicates that the returned content cound not parsed by angular(it's invalid json string), so we need check the server returns, it may be a 404, or 500 server error... Commented Apr 20, 2017 at 6:10
  • @aspark hmm strange. I'll update the question wit what I see in the headers for the call on the network tab in chrome Commented Apr 20, 2017 at 6:26
  • 1
    but you have not show the response body, or you can confirm the response is valid json, i guess the response is html which need authorise Commented Apr 20, 2017 at 6:32

1 Answer 1

0

My guess is your web api has exception when initialize Controller.

Run debugger and check all Common Language Runtime Exceptions in Exception Settings to see any others exception throw.

Sign up to request clarification or add additional context in comments.

1 Comment

No, I don't believe I do. On my controller I have a constructor and I have an initial HttpGet Method that returns a base view and breakpoints in both of these get hit and the base view gets returned.

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.