Angular 4 DB Access Model

I am currently learning Angular 4 and I have a task to create an organization chart visualization. I found several options on how to do this and I chose this one . I chose it because it uses a SQL database which I have to use as well. The only problem for me is that the project is written in AngularJS, that I have to port it to Angular 4 and I cannot think of a correct way to do this.

I am using Visual Studio 2015, an empty ASP.NET Web Application project with MVC folder layout and this is what I have done so far:

  • Normal Angular setup (npm install, AppModule bootstrap ...)
  • I have a database and I created an ADO model.
  • I have a HomeController.cs folder in controllers.

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. I have employees.service.ts in which I am trying to get a JSON object full of employees.

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. My folder structure looks like this

Folder structure

Additional Information:

  • EmployeesService is registered as a provider in the AppModule
  • EmployeesComponent calls the service getEmployees () method in init.
  • This code is just a POC, all I want to do is write the JSON output.
  • The only way out for me so far is: ERROR Error: Uncaught (in promise): Response with status: 404 Not Found for URL: http://localhost:3002/Home/GetEmployees

My questions (link to numbers in code):

  • How can I check if this url is correct and if not to which url should I change it?
  • Are headings needed? I've seen some ways to initialize them, but that just doesn't make any sense to me.
  • Is there something else that I am missing that I am not aware of?

Recent Notes:

Using the tutorial from the link above I was able to get it running, so I think my DB and DB model is ok. If you think this question is missing some important information, let me know in the comments and I'll add. As I mentioned earlier, I am new to Angular and I might be ignoring some important things.

+3


source to share


2 answers


You should take a closer look at attribute routing as well as how to create the right REST-ful API. The Employee object must have its own controller, not nested within the Home controller.

The problem you are currently facing is that the GetEmployees route is not available as there is already a default GET method defined in your HomeController method (Index () method).



Add a new EmployeesController to the Controllers folder and add the GetEmployees method . This way you should be able to get all employees with REST-ful using a call like http: // localhost: 3002 / Employees to get all employees, which also resonates much better with how Angular 2 services are supposed to be built. (I am assuming you mean Angular 2 and not 4 , right?)

+2


source


I found out that I was having problems with the correct url. Due to some tweaking I made in Index.cshtml I managed to break it somehow and instead http://localhost/OrgChart/Home/GetEmployees

I used different links which were wrong. This is the workaround I came up with.

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

      

This is what Index.cshtml looks like . Without href="~/src/"

I cannot access the script, but because of this, the url ends up crashing. Hence, a workaround.



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>

      

I'm not one hundred percent sure I'm doing the right thing, but it works so far. I will be glad if you find some risks or errors in this workaround and point them out.

0


source







All Articles