This is the continues of
Angular 8 - CRUD Operations - Part One. In this article, we will learn about Angular Routing and Angular Services and How to make a Web API with entity framework using NORTHWND SQL Server database.
Angular Routing
The Angular Router is used to navigate between views or pages that are triggered by the user's actions. The navigation or view changes happen when the user clicks on the link, click on the button, or enters the URL from the browser address bar.
In this sample, I am converting my website which was built in AngularJS into Angular 8. So, navigations are according to my website need.
First you need to create a few components using CLI command,
ng generate component blog
ng generate component article
Now go to app-routing.module.ts file and add the component references and redirect routing.
- import { NgModule } from '@angular/core';
- import { Routes, RouterModule } from '@angular/router';
- import { EmployeeComponent } from './employee/employee.component'
- import { AboutComponent } from './about/about.component'
- import { ContactComponent } from './contact/contact.component'
- import { BlogComponent } from './blog/blog.component'
- import { ArticleComponent } from './article/article.component'
- import { CodingComponent } from './coding/coding.component'
- import { SnippetComponent } from './snippet/snippet.component'
- import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
-
- const routes: Routes = [
- {path: 'employee', component: EmployeeComponent},
- {path: 'about', component: AboutComponent},
- {path: 'contact', component: ContactComponent},
- {path: 'blog', component: BlogComponent},
- {path: 'article', component: ArticleComponent},
- {path: 'coding', component: CodingComponent},
- {path: 'snippet', component: SnippetComponent},
- { path: '', redirectTo: '/home', pathMatch: 'full' },
- { path: '**', component: PageNotFoundComponent }
- ];
-
- @NgModule({
- imports: [RouterModule.forRoot(routes)],
- exports: [RouterModule]
- })
- export class AppRoutingModule { }
Add a new navbar component and add the following code,
- <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
- <a class="navbar-brand logo" href="#">DotNetBuild</a>
- <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
- <span class="navbar-toggler-icon"></span>
- </button>
-
- <div class="collapse navbar-collapse" [ngClass]="{ 'show': navbarOpen }" id="navbarSupportedContent">
- <ul class="navbar-nav mr-auto">
- <li class="nav-item active">
- <a class="nav-link" routerLink="" routerLinkActive="active">Home <span class="sr-only">(current)</span></a>
- </li>
- <li class="nav-item">
- <a class="nav-link" routerLink="/employee" routerLinkActive="active">Employee</a>
- </li>
- <li class="nav-item">
- <a class="nav-link" routerLink="/blog" routerLinkActive="active">Blogs</a>
- </li>
- <li class="nav-item">
- <a class="nav-link" routerLink="/article" routerLinkActive="active">Articles</a>
- </li>
- <li class="nav-item">
- <a class="nav-link" routerLink="/coding" routerLinkActive="active">Coding Tips</a>
- </li>
- <li class="nav-item">
- <a class="nav-link" routerLink="/snippet" routerLinkActive="active">Code Snippet</a>
- </li>
- <li class="nav-item">
- <a class="nav-link" routerLink="/about" routerLinkActive="active">About Us</a>
- </li>
- <li class="nav-item">
- <a class="nav-link" routerLink="/contact" routerLinkActive="active">Contact Us</a>
- </li>
- </ul>
- <ul class="navbar-nav ">
- <li class="nav-item">
- <a class="nav-link" href="#"><fa-icon [icon]='faSearch'></fa-icon></a>
- </li>
- <li class="nav-item">
- <a class="nav-link" href="#"><fa-icon [icon]='faBell'></fa-icon></a>
- </li>
- <li class="nav-item">
- <a class="nav-link" href="#"><fa-icon [icon]='faUser'></fa-icon></a>
- </li>
- <li class="nav-item dropdown">
- <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true"
- aria-expanded="false">User1</a>
- <div class="dropdown-menu">
- <a class="dropdown-item" href="#">User2</a>
- <a class="dropdown-item" href="#">User3</a>
- <a class="dropdown-item" href="#">Kids</a>
- </div>
- </li>
- </ul>
- </div>
- </nav>
Go to app.component.html and navbar component and router-outlet and app-footer.
- <div>
- <app-navbar></app-navbar>
- </div>
- <div class="container">
- <router-outlet></router-outlet>
- </div>
- <div>
- <app-footer></app-footer>
- </div>
In the given html, I have used Bootstrap, Font awesome and AngularJS Material.
Let's add the following styles and java scripts into the application before going further.
Go to Terminal and install the following,
npm install bootstrap –-save
npm install jquery –save
npm install --save @angular/material
npm install font-awesome --save
Once you have installed everything then you will find these files in your node module folder,
node_modules/jquery/dist/jquery.min.js
node_modules/bootstrap/dist/css/bootstrap.min.css
node_modules/bootstrap/dist/js/bootstrap.min.js
Then you have to update your angular.json file,
- "styles": [
- "src/styles.scss",
- "node_modules/bootstrap/dist/css/bootstrap.min.css"
- ],
- "scripts": [
- "node_modules/jquery/dist/jquery.min.js",
- "node_modules/bootstrap/dist/js/bootstrap.min.js"
- ]
Run the application to see the output,
Provide the following command to run.
Give http://localhost:4200/ in browser.
If you click on any menu, every menu will redirect to the provided endpoint.
We are done here with the routing part, now let's build a Web API with Entity framework and SQL Server database.
Web API
The ASP.NET Web API is an extensible framework for creating HTTP based services that can be accessed in different applications on different platforms such as web, windows, mobile etc. It works the same way as ASP.NET MVC web applications do, except that it sends data as a response instead of html view. It supports HTTP protocol only.
Let’s create a Web API using Visual Studio 2019.
- Start Visual Studio 2019
- Create a New WEB Projects and Select Web API
- Give a name and browse location
- Click OK
Once the project is created, right click on Models and click on Add >> Add New Item and select ADO.NET Entity Data Model from installed Data templates. Follow these steps,
- Provide name of model
- Choose EF designer from database model contents and click next
- Choose you data connection, make new if not available
- Provide server name and select database from list
- Test connection and click next
- Select entity framework version
- Choose database tables and give model namespace and click finish
Database diagram
Web API structure
Add a new API controller in Controller folder and CRUD functions.
Now try to hit a Web API function to get the data, you will get this error,
To remove this error, add these lines of code on Global.asax file in Application_Start function.
- GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
- .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
- GlobalConfiguration.Configuration.Formatters
- .Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
Now try to hit the function again, then you will able to see the data in JSON format.
Enable CORS
This is an important part when you create a new Web API. CORS stands for Cross-Origin Resource Sharing. It is a mechanism that allows restricted resources on a web page to be requested from another domain, outside the domain from which the resource originated. A web page may freely embed images, stylesheets, scripts, iframes, and videos.
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest follows the same-origin policy. So, a web application using XMLHttpRequest could only make HTTP requests to its own domain. To improve web applications, developers asked browser vendors to allow XMLHttpRequest to make cross-domain requests.
Enable CORS
Now let's 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
Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method,
- public static void Register(HttpConfiguration config)
- {
-
- config.EnableCors();
-
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
OR,
- public static void Register(HttpConfiguration config)
- {
- var cors = new EnableCorsAttribute("*", "*", "*");
- config.EnableCors(cors);
-
-
-
- config.MapHttpAttributeRoutes();
-
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
Now we are done with WEB API part, let’s move on Angular Service part.
Angular Services
The main use of services is to organize and share business logic, models or data and functions with different components of an Angular application. Angular services are singleton objects (it is very important, so we can share it easily through project) which get instantiated only once during the lifetime of an application. They contain methods that maintain data throughout the life of an application, i.e. data does not get refreshed and is available all the time.
Let’s create a new Service and call Web API functions in it.
The best way to create a Service in Angular is with Visual Studio Code. Go to Terminal and hit the command, that will add a new service in an application.
No go to employee.service.ts file and add the following code,
- import { Injectable } from '@angular/core';
- import { HttpClient } from '@angular/common/http';
- import { HttpHeaders } from '@angular/common/http';
- import { Observable } from 'rxjs';
- import { Employee } from './employee';
-
- @Injectable({
- providedIn: 'root'
- })
- export class EmployeeService {
- url = 'http://localhost:49210/Api/Employee';
-
- constructor(private http: HttpClient) { }
-
- getEmployees(): Observable<Employee[]> {
- return this.http.get<Employee[]>(this.url + '/GetEmployees');
- }
-
- getEmployee(employeeId: string): Observable<Employee> {
- return this.http.get<Employee>(this.url + '/GetEmployee/' + employeeId);
- }
- createEmployee(employee: Employee): Observable<Employee> {
- const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
- return this.http.post<Employee>(this.url + '/InsertEmployee/', employee, httpOptions);
- }
-
- updateEmployee(employee: Employee): Observable<Employee> {
- const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
- return this.http.put<Employee>(this.url + '/UpdateEmployee/', employee, httpOptions);
- }
-
- deleteEmployee(employeeid: string): Observable<number> {
- const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
- return this.http.delete<number>(this.url + '/DeleteEmployee?id=' + employeeid, httpOptions);
- }
- }
In a given service class, we have file function for CRUD operations along with Web API root path. You can change api root path according to your API. We are done here with Angular Service part.
Conclusion
In this article, we have learned about angular routing, services and how to make Web API using Entity framework with SQL Server database. The next part is coming with Angular implementation for CRUD operations. Stay tuned!