Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

AngularJS Hosting Europe - HostForLIFE :: Use the ASP.NET Web API in Angular to Retrieve Data From a Database

clock June 25, 2025 09:45 by author Peter

In this article, I will explain how to call ASP.NET web API in your Angular project step by step. You need to enable CORS in your web API and fetch data from web API. It is easy to call API in Angular.


Step 1
Open SQL server of your choice and create a table and insert some records.

    CREATE TABLE [dbo].[Employee](  
        [Employee_Id] [int] IDENTITY(1,1) NOT NULL,  
        [First_Name] [nvarchar](50) NULL,  
        [Last_Name] [nvarchar](50) NULL,  
        [Salary] [money] NULL,  
        [Joing_Date] [nvarchar](50) NULL,  
        [Department] [nvarchar](50) NULL,  
     CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
    (  
        [Employee_Id] ASC  
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
    ) ON [PRIMARY]  
      
    GO  

Step 2

Open Visual Studio, click on New Project and create an empty web API application project.

After clicking on New Project, one window will appear. Select Web from the left panel, choose ASP.NET Web Application, give a meaningful name to your project, and then click on OK as shown in the below screenshot.

After clicking on OK one more window will appear; choose empty, check on empty Web API checkbox then click on OK as shown in the below screenshot

After clicking OK, the project will be created with the name of WebAPICRUD_Demo.

Step 3
Add Entity Framework now. For that, right click on Models folder, select Add, then select New Item, then click on it.

After clicking on a New item, you will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name MyModel (this name is not mandatory you can give any name) and click on Add.

After you click on "Add a window", the wizard will open, choose EF Designer from the database and click Next.

After clicking on Next a window will appear. Choose New Connection. Another window will appear, add your server name if it is local then enter a dot (.). Choose your database and click on OK.

The connection will be added. If you wish to save connect as you want. You can change the name of your connection below. It will save connection in web config then click on Next.

After clicking on NEXT another window will appear to choose database table name as shown in the below screenshot then click on Finish. Entity framework will be added and the respective class gets generated under the Models folder.

Following class will be added,
    namespace WebAPICURD_Demo.Models  
    {  
        using System;  
        using System.Collections.Generic;  
          
        public partial class Employee  
        {  
            public int Employee_Id { get; set; }  
            public string First_Name { get; set; }  
            public string Last_Name { get; set; }  
            public Nullable<decimal> Salary { get; set; }  
            public string Joing_Date { get; set; }  
            public string Department { get; set; }  
        }  
    }  

Step 4
Right click on Controllers folder, select Add, then choose Controller as shown in the below screenshot.


After clicking on the controller a window will appear to choose Web API 2 Controller-Empty, click on Add.


Fetch Data From Database Using ASP.NET Web API In Angular
After clicking on Add, another window will appear with DefaultController. Change the name to EmployeeController then click on Add. EmployeeController will be added under Controllers folder. Remember don’t change the Controller suffix for all controllers, change only highlight, and instead of Default just change Home as shown in the below screenshot.


Complete code for controller
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Net;  
    using System.Net.Http;  
    using System.Web.Http;  
    using WebAPICURD_Demo.Models;  
      
    namespace WebAPICURD_Demo.Controllers  
    {  
        public class EmployeeController : ApiController  
        {  
             
            private EmployeeEntities _db;  
            public EmployeeController()  
            {  
                _db =new EmployeeEntities();  
            }  
            public IEnumerable<Employee> GetEmployees()  
            {  
                return _db.Employees.ToList();  
            }  
        }  
    }  


Step 5
Now, enable CORS in the WebService app. First, add the CORS NuGet package. In Visual Studio, from the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command.
Install-Package Microsoft.AspNet.WebApi.Cors  

This command installs the latest package and updates all dependencies, including the core Web API libraries.

Step 6
Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method.

Add namespace
using System.Web.Http.Cors;  

Add the following line of code,
    EnableCorsAttribute cors = new EnableCorsAttribute("*","*","*");  
    config.EnableCors(cors);  


Complete WebApiConfig.cs file code
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web.Http;  
    using System.Web.Http.Cors;  
      
    namespace WebAPICURD_Demo  
    {  
        public static class WebApiConfig  
        {  
            public static void Register(HttpConfiguration config)  
            {  
                // Web API configuration and services  
                  
                // Web API routes  
                config.MapHttpAttributeRoutes();  
      
                config.Routes.MapHttpRoute(  
                    name: "DefaultApi",  
                    routeTemplate: "api/{controller}/{id}",  
                    defaults: new { id = RouteParameter.Optional }  
                );  
      
                EnableCorsAttribute cors = new EnableCorsAttribute("*","*","*");  
                config.EnableCors(cors);  
            }  
        }  
    }  


Step 6
Open Visual Studio Code and create a new Angular project.
    ng new MyDemo  

Compile your project
    cd MyDemo  

Open your project in the browser,
    ng serve --open  

Step 7
Install bootstrap in your project and import in style.css file,
    npm install bootstrap –save  

    @import 'node_modules/bootstrap/dist/css/bootstrap.min.css';  


Step 8
Open terminal create component,
    ng g c employee-list  

Step 9
Open app.module.ts file and import httpModule
    import { BrowserModule } from '@angular/platform-browser';  
    import { NgModule } from '@angular/core';  
    import {HttpClientModule, HttpClient} from '@angular/common/http';  
      
    import { AppComponent } from './app.component';  
    import { from } from 'rxjs';  
    import { EmployeeListComponent } from './employee-list/employee-list.component';  
      
    @NgModule({  
      declarations: [  
        AppComponent,  
        EmployeeListComponent  
      ],  
      imports: [  
        BrowserModule,  
        HttpClientModule  
      ],  
      providers: [],  
      bootstrap: [AppComponent]  
    })  
    export class AppModule { }  


Step 10
Open employee-list component.ts file and add the following code,
    import { HttpClientModule, HttpClient } from '@angular/common/http';  
    import { Component, OnInit } from '@angular/core';  
      
    @Component({  
      selector: 'app-employee-list',  
      templateUrl: './employee-list.component.html',  
      styleUrls: ['./employee-list.component.css']  
    })  
    export class EmployeeListComponent implements OnInit {  
      
      constructor(private httpService: HttpClient) { }  
      employees: string[];  
      ngOnInit() {  
        this.httpService.get('http://localhost:52202/api/employee').subscribe(  
          data => {  
           this.employees = data as string [];  
          }  
        );  
      }  
      
    }  


Step 11
open employee-list.component.html and add the following code,
    <div class="container py-5">  
        <h3 class="text-center text-uppercase">List of Employees</h3>  
        <table class="table table-bordered table-striped">  
            <thead>  
                <tr class="text-center text-uppercase">  
                    <th>Employee ID</th>  
                    <th>First Name</th>  
                    <th>Last Name</th>  
                    <th>Salary</th>  
                    <th>Joining Date</th>  
                    <th>Department</th>  
                  </tr>  
            </thead>  
            <tbody>  
              <tr *ngFor="let emp of employees">  
                <td>{{emp.Employee_Id}}</td>  
                <td>{{emp.First_Name}}</td>  
                <td>{{emp.Last_Name}}</td>  
                <td>{{emp.Salary}}</td>  
                <td>{{emp.Joing_Date}}</td>  
                <td>{{emp.Department}}</td>  
              </tr>  
            </tbody>  
          </table>  
        </div>  


Step 12
Add your employee-list.component.html selector in app.component.html
    <app-employee-list></app-employee-list>  

Step 13
Run your project in browser.



AngularJS Hosting Europe - HostForLIFE :: New Development Site Angular

clock June 17, 2025 09:19 by author Peter

Note: The publication date of this article is January 10, 2025. This article series is unquestionably an AI result or byproduct.  This piece might represent a change in my writing style since it makes use of AI results that I understand, like those related to StackBlitz | Instant Dev Environments, to make it easier to write and easier to read. Angular first launched in 2016, Angular's home page used to be at angular.io for years. Recently, I found that a new Angular Development Site has been created. This article records some info about this event. 

Official Home: May, 2024

Previous Sites:
Angular - Introduction to the Angular docs --- Angular.io --- v17

Angular - Introduction to the Angular docs --- Angular.io --- v18


Tutorial:

Tutorials • Angular



AngularJS Hosting Europe - HostForLIFE :: Angular State Management with NGXS

clock June 12, 2025 10:33 by author Peter

Managing shared state between components gets more difficult as your Angular application expands.  NGXS (pronounced "nexus") offers a simple, intuitive, and powerful state management pattern for Angular apps, based on the principles of Redux but with a more Angular-friendly approach. This post will discuss how to effectively manage application state by configuring and utilizing NGXS.

Why NGXS?
NGXS provides:

  • A simple API using decorators and observables.
  • Type-safe state and actions.
  • Built-in support for plugins (logger, devtools, storage).
  • Easy-to-understand state mutation via actions.

Step 1. Install NGXS
Use the Angular CLI to install the NGXS packages:
npm install @ngxs/store --save


Optional DevTools and plugins:
npm install @ngxs/devtools-plugin @ngxs/logger-plugin --save

Step 2. Create a State Model
Create an interface to define your state:
// models/todo.model.ts
export interface Todo {
  id: number;
  title: string;
  completed: boolean;
}

Step 3. Define Actions
Actions are plain classes that represent events in your app.

// actions/todo.actions.ts
export class AddTodo {
  static readonly type = '[TODO] Add';
  constructor(public payload: string) {}
}

export class ToggleTodo {
  static readonly type = '[TODO] Toggle';
  constructor(public id: number) {}
}

Step 4. Create the State
Define the NGXS state using the @State() decorator.
// state/todo.state.ts
import { State, Action, StateContext, Selector } from '@ngxs/store';
import { AddTodo, ToggleTodo } from '../actions/todo.actions';
import { Todo } from '../models/todo.model';

@State<Todo[]>({
  name: 'todos',
  defaults: []
})
export class TodoState {

  @Selector()
  static getTodos(state: Todo[]) {
    return state;
  }

  @Action(AddTodo)
  add({ getState, patchState }: StateContext<Todo[]>, { payload }: AddTodo) {
    const state = getState();
    const newTodo: Todo = { id: Date.now(), title: payload, completed: false };
    patchState([...state, newTodo]);
  }

  @Action(ToggleTodo)
  toggle({ getState, patchState }: StateContext<Todo[]>, { id }: ToggleTodo) {
    const state = getState();
    const updated = state.map(todo =>
      todo.id === id ? { ...todo, completed: !todo.completed } : todo
    );
    patchState(updated);
  }
}


Step 5. Register the State in the App Module

// app.module.ts
import { NgxsModule } from '@ngxs/store';
import { TodoState } from './state/todo.state';

@NgModule({
  declarations: [...],
  imports: [
    NgxsModule.forRoot([TodoState]),
  ],
  bootstrap: [...]
})
export class AppModule {}

Step 6. Use the State in Components
// app.component.ts
import { Store, Select } from '@ngxs/store';
import { Observable } from 'rxjs';
import { TodoState } from './state/todo.state';
import { AddTodo, ToggleTodo } from './actions/todo.actions';

@Component({...})
export class AppComponent {
  @Select(TodoState.getTodos) todos$: Observable<Todo[]>;

  constructor(private store: Store) {}

  addTodo(title: string) {
    this.store.dispatch(new AddTodo(title));
  }

  toggleTodo(id: number) {
    this.store.dispatch(new ToggleTodo(id));
  }
}

Conclusion
NGXS brings a clean and declarative way to manage state in Angular apps. With actions, selectors, and plugins, it streamlines complex state flows into something more maintainable and scalable. Happy coding !



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in