Angular 2和MVC路由 [英] Angular 2 and MVC routing

查看:85
本文介绍了Angular 2和MVC路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助,因为我无法使Angular在Visual Studio 2017中正确调用API.这是我的代码的一部分(我已导入并注入了Angular正常工作所需的一切):

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);
        });

    }

内部Startup.cs:

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" });
});

和test.cs控制器:

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"}
            });
        }
    }
}

通过使用邮递员http://localhost:65040/api/employees,我从TestController获取数据. 我还需要什么来从Angular GetCustomerInfoService中获取数据?现在我收到以下错误:

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:

在处理请求时发生未处理的异常. NodeInvocationException:未捕获(承诺):ReferenceError:未定义XMLHttpRequest ReferenceError:未定义XMLHttpRequest

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

推荐答案

您的路线完全是错误的.您为

Your route is just plain wrong. You define route for

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

并注册test/api/employees,但是您呼叫/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() { ... }
}

由于路由中间件未找到称为"api"的控制器,因此它将回退到SpaServices后备路线,这将加载角度应用程序.

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() { ... }
}

或者您为所有api控制器定义标准路由:

Or you define a standard route for all api controllers:

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

现在这应该足够了

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

但是后一个可能与您的HomeController冲突,因为它将把所有控制器都视为"Api"控制器(阅读:甚至/api/home都将路由到HomeController).

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).

这篇关于Angular 2和MVC路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆