Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 access DB model

I'm currently learning Angular 4 and I have a task to create an organization chart visualization. I found multiple options how to do it and I picked this one. I chose it because it utilizes SQL database which I'm also supposed to use. The only problem for me is since the project is written in AngularJS that I have to migrate it to Angular 4 and I'm failing to come up with the proper way to do it.

I'm using Visual Studio 2015, empty ASP.NET web application project with MVC folder layout and this is what I have done so far:

  1. Usual Angular setup (npm install, AppModule bootstrap...)
  2. I have a database running and I created an ADO model.
  3. I have a HomeController.cs in Controllers folder.

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 an employees.service.ts in which I'm 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

Folders structure

Additional info:

  1. EmployeesService is registered as a provider in AppModule
  2. EmployeesComponent calls service method getEmployees() on init.
  3. This code is just a POC, all I want to do is log a JSON output.
  4. The only output 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 are (referring to numbers in code):

  1. How can I check that this URL is correct and if not to what url should I change it to?
  2. Do I need headers? I saw some ways how to initialize them but it's just not making any sense for me.
  3. Is there something else I'm missing and I'm not aware of it?

Last notes:

Using the tutorial from the link on the top I was able to make it run so I guess that my DB and DB model are OK. If you think this question lacks some important info let me know in comments and I'll add it. As I mentioned before, I'm new to Angular and I might be overlooking some important stuff.

like image 851
mat.hudak Avatar asked Apr 17 '26 23:04

mat.hudak


1 Answers

You should take closer look at attribute routing and also how to create a proper REST-ful API. The Employee entity should have its own controller, instead of being nested in the Home-controller.

The problem that you're facing right now is due to the route GetEmployees not being available, as there is already a default GET method defined on your HomeController (The Index() method).

Add a new EmployeesController in the Controllers folder, and put the GetEmployees method in there. In that way, you would be able to get all employees in a REST-ful way using a call like http://localhost:3002/Employees to get all employees, which also resonates much better with the way that Angular 2 services are supposed to be built. (I'm guessing that you mean Angular 2 and not 4, right?)

like image 53
J.N. Avatar answered Apr 19 '26 13:04

J.N.