Angular 2 and MVC routing

2019-08-27 06:47发布

问题:

I need some help as I cannot make Angular to call correctly an API inside Visual Studio 2017. Here is part of my code(I have imported and injected everything Angular needs as to work):

@Injectable()
export class GetCustomerInfoService {

    constructor(private http: HttpClient) { }

    getResults() {
        return this.http.get('http://localhost:65040/api/employees');
    }
}


@Component({
    selector: 'apply',
    templateUrl: './apply.component.html',
    providers: [GetCustomerInfoService]
})
export class ApplyComponent {

    constructor(private customerInfo: GetCustomerInfoService) {
        this.customerInfo.getResults().subscribe(result => {
            console.log(result);
        });

    }

Inside Startup.cs:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
    routes.MapSpaFallbackRoute(
        name: "spa-fallback",
        defaults: new { controller = "Home", action = "Index" });
});

and test.cs Controller:

namespace Coc.Controllers
{
    public class TestController : Controller
    {
        [HttpGet("api/employees")]
        public JsonResult GetEmployees()
        {
            return new JsonResult(new List<object>()
            {
                new {employeeid = 01989, Name = "John Patrick"},
                new {employeeid = 01987, Name= "Michael"},
                new {employeeid = 01988, Name= "Akhil Mittal"}
            });
        }
    }
}

By using postman http://localhost:65040/api/employees I am getting the data from TestController. What do I need as to get the data from Angular GetCustomerInfoService as well? Now I am getting the following error:

An unhandled exception occurred while processing the request. NodeInvocationException: Uncaught (in promise): ReferenceError: XMLHttpRequest is not defined ReferenceError: XMLHttpRequest is not defined

回答1:

Your route is just plain wrong. You define route for

routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}");

and register test/api/employees, but you call /api/employees.

public class TestController : Controller
{
    // This route is relative to the /test path, because that's the name of the controller
    [HttpGet("api/employees")]
    public JsonResult GetEmployees() { ... }
}

Since the routing middleware finds no controller called "api", it will fall back to the SpaServices fallback route, which loads the angular application.

You probably want make something like this

[Route("api/employees")]
public class TestController : Controller
{
    [HttpGet]
    public JsonResult GetEmployees() { ... }

    // or this, but not recommended, to to harder maintenance. Notice the slash in front of the route
    [HttpGet("/api/employees")]
    public JsonResult GetEmployees() { ... }
}

Or you define a standard route for all api controllers:

routes.MapRoute(
    name: "defaultApi",
    template: "api/{controller}/{id?}");

Now this should be sufficient

public class TestController : Controller
{
    // Just the verb
    [HttpGet]
    public JsonResult GetEmployees() { ... }
}

But the later one may conflict with your HomeController, as it will treat all controllers as "Api" controllers (read: even /api/home would route to HomeController).



回答2:

Your error suggests that your application is being run on Node. This might occur for example if you have server-side pre-rendering, as is the case with the Angular template that comes with Visual Studio.

However, XMLHttpRequest is only available in the browser. According to this question, you need to install support for XMLHttpRequest on Node. Alternatively, you could try disabling server-side pre-rendering so that your Angular code is only run in the browser.

I believe it is HttpClient that needs XMLHttpRequest. Therefore you could also try the older Http instead of HttpClient.