繁体   English   中英

Angular 4访问DB模型

[英]Angular 4 access DB model

我目前正在学习Angular 4,我有一个创建组织结构图可视化的任务。 我发现了多个选项如何做到这一点,我拿起这一个 我选择它是因为它使用了我也应该使用的SQL数据库。 对我来说唯一的问题是因为项目是用AngularJS编写的,我必须将它迁移到Angular 4,而我却没有找到正确的方法来实现它。

我正在使用Visual Studio 2015,使用MVC文件夹布局清空ASP.NET Web应用程序项目,这是我到目前为止所做的:

  1. 通常的角度设置( npm install,AppModule bootstrap ...
  2. 我有一个运行的数据库,我创建了一个ADO模型。
  3. 我在Controllers文件夹中有一个HomeController.cs

HomeController.cs

using Pas.Angular.OrgChart.Models;

namespace Pas.Angular.OrgChart.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetEmployees()
        {
            List<Employees> emp = new List<Employees>();
            using (EmployeesDBEntities dc = new EmployeesDBEntities())
            {
                emp = dc.Employees.OrderBy(a => a.PositionID).ToList();
            }
            return new JsonResult
            {
                Data = emp,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
    }
}
  1. 我有一个employees.service.ts ,其中我试图获得一个充满员工的JSON对象。

employees.service.ts

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

import "rxjs/add/operator/toPromise";

@Injectable()
export class EmployeesService {
    private headers: Headers;
    private baseUrl = "/Home/GetEmployees" // Question no. 1


    constructor(private http: Http) {
       // Question no. 2
    }

    getEmployees(): Promise<JSON[]> {
        return this.http.get(this.baseUrl) // Question no. 2
            .toPromise()
            .then(response => response.json())
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.log("An error has occurred: ", error);
        return Promise.reject(error.message || error);
    }
}

RouteConfig.cs

namespace Pas.Angular.OrgChart
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}
  1. 我的文件夹结构如下所示

文件夹结构

附加信息:

  1. EmployeesService在AppModule中注册为提供者
  2. EmployeesComponent在init上调用服务方法getEmployees()
  3. 这段代码只是一个POC,我想做的就是记录一个JSON输出。
  4. 到目前为止,我唯一的输出是: ERROR Error: Uncaught (in promise): Response with status: 404 Not Found for URL: http://localhost:3002/Home/GetEmployees

我的问题是参考代码中的数字 ):

  1. 如何检查此URL是否正确,如果不是,我应该将其更改为哪个URL?
  2. 我需要标题吗? 我看到了一些如何初始化它们的方法,但这对我没有任何意义。
  3. 还有其他我想念的东西,我不知道吗?

最后说明:

使用顶部链接的教程我能够让它运行所以我猜我的数据库和数据库模型都没问题。 如果您认为这个问题缺少一些重要信息,请在评论中告诉我,我会添加它。 正如我之前提到的,我是Angular的新手,我可能会忽略一些重要的东西。

您应该仔细查看属性路由以及如何创建适当的REST-ful API。 Employee实体应该有自己的控制器,而不是嵌套在Home-controller中。

您现在面临的问题是由于GetEmployees路径不可用,因为HomeController上已经定义了默认的GET方法( Index()方法)。

Controllers文件夹中添加一个新的EmployeesController ,并将GetEmployees方法放在那里。 通过这种方式,您可以使用http:// localhost:3002 / Employees之类的呼叫以REST-ful方式获得所有员工,以获得所有员工,这也与Angular 2服务的方式产生更好的共鸣要建成。 (我猜你的意思是Angular 2而不是4 ,对吗?)

我发现我的网址有问题。 由于我在Index.cshtml中做了一些自定义,我设法以某种方式打破它而不是http://localhost/OrgChart/Home/GetEmployees我使用的是不同的链接,这些都是不正确的。 这是我提出的解决方法。

employees.service.ts

import { Injectable, Inject } from "@angular/core"; //In order to inject DOCUMENT
import { Headers, Http } from "@angular/http";
import { DOCUMENT } from "@angular/platform-browser";

import "rxjs/add/operator/toPromise";

@Injectable()
export class EmployeesService {
    private empUrl = "Home/GetEmployees";
    private baseUrl: string;

    constructor(private http: Http, @Inject(DOCUMENT) private document: any) {
        // document injection and the way how to get the base URL
        this.baseUrl = this.document.location.href + this.empUrl;
        console.log(this.baseUrl);
        // This will create a correct URL
        // http://localhost/OrgChart/Home/GetEmployees
    }

    getEmployees(): Promise<any> {
        return this.http.get(this.baseUrl)
            .toPromise()
            .then(response => response.json())
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.log("An error has occurred: ", error);
        return Promise.reject(error.message || error);
    }
}

这就是Index.cshtml头部的样子。 没有href="~/src/"我无法访问脚本,但也因为它,URL最终出现故障。 因此,解决方法。

Index.cshtml

<head>
    <title>PAS org chart</title>
    <base href="~/src/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style> ... </style>
    <script src="~/node_modules/core-js/client/shim.min.js"></script>
    <script src="~/node_modules/zone.js/dist/zone.js"></script>
    <script src="~/node_modules/systemjs/dist/system.src.js"></script>
    <script src="systemjs.config.js"></script>
    <script>
        System.import('main.js').catch(function (err) { console.error(err); });
    </script>
</head>

我不是百分百肯定我做的是正确的事情,但到目前为止,它确实是我的作品。 如果您在此变通方法中发现一些风险或错误并将其指出,我将很高兴。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM