.NET Core 2.0 With Angular 4 and MySQL, Part 9: Angular HTTP

DZone 's Guide to

.NET Core 2.0 With Angular 4 and MySQL, Part 9: Angular HTTP

If you want to make a web application, it's important that it can send and receive requests so, you know, people can actually visit it. Learn how to make this happen!

· Web Dev Zone ·
Free Resource

While sending HTTP requests towards our server, we need to use the HTTP Angular protocol. Of course, we may handle all the HTTP requests from every component and process the response as well, but it is not a good practice. It is much better to make the repository for your requests and then send the request URL to that repository. The repository should take care of the rest.

How do we achieve this?

That's the topic of this blog post.

If you want to see all the basic instructions and complete navigation for this series, check out the following link: Introduction page for this tutorial.

For the previous part check out: Part 8 - Creating Angular4 client side - Navigation and routing

The source code is available at GitHub .NET Core, Angular 4 and MySQL. Part 9 - Source Code

About HttpClientModule

The thing that matters is that we are going to use the new HttpClientModule introduced in Angular 4.3 and not the old HttpModule. The new module gives us some advantages with processing responses and handling errors as well. With the old HttpModule, we would have to map our response and convert it to the JSON. Consequently, we would have to use the RxJS library because this library enables the usage of the map function. With the new HttpClientModule, the JSON response is set by default. Thus our project requires no result conversion at all.

The one way to check out our Angular version is to start the application and to open developer tools. We will see the version in the <app-root> tag:

Working With Environment Files

While this project is in development mode the server's endpoint address is the http://localhost:5000. With the application in the production environment, the endpoint is different, something like www.accountowner.com. What we want is that Angular takes care of that. So in the development mode, it should send requests towards localhost:5000, and in the production environment to some other address.

Let's implement that.

In the side-bar of the visual studio code, search for the environments folder. Inside that folder, you are going to find two files, environment.prod.ts and environment.ts. We are going to use the first one for configuring the production and the second one for configuring the development environment.

It is time for us to modify these files.


export const environment = {
  production: true,
  urlAddress: 'http://www.accountowner.com'


export const environment = {
  production: false,
  urlAddress: 'http://localhost:5000'

Now we are going to create the service which will provide us with the valid environment urlAddress.

Inside the app folder, create a new folder and name it shared. Then in that folder create a new one and name it services. Finally, create the new file environment-url.service.ts:

We could do this using the AngularCLI command as well:

ng g service shared/services/environment-url

About the Angular Services

Services are just classes, which provide us some business logic relevant to our components. These services must be injected into a component using constructor injection. Furthermore, your code becomes more maintainable and readable.

When we want to use a service, we need to inject it into a component's constructor. Therefore, it is always decorated with the @Injectable decorator. Use services whenever you have some code that you can reuse in other components, or extract part of the code from your components. To make a service work, we must import it into our app.module.ts file.

Let's continue our work with the environment files by modifying the environment-url.service.ts file:

import { Injectable } from '@angular/core';
import { environment } from './../../../environments/environment';

export class EnvironmentUrlService {

  public urlAddress: string = environment.urlAddress;

  constructor() { }


The urlAddress property accepts the value of the urlAddress defined in the environment file. Angular knows if it is a production or development environment (because of the "production" property values inside both environment files) and is going to supply us with a valid value for that urlAddress.

Now we need to import this service into our app.module.ts file:

import { EnvironmentUrlService } from './shared/services/environment-url.service';

Place it inside the  providers array as well:

providers: [

Creating an Angular Repository File

Let's configure the HttpClientModule and create the repository service.

First, we need to import the HttpClientModule inside the app.module.ts file:

import { HttpClientModule } from '@angular/common/http';

Then let's place it inside the imports array:

imports: [
      { path: 'home', component: HomeComponent },
      { path: '404', component : NotFoundComponent},
      { path: '', redirectTo: '/home', pathMatch: 'full' },
      { path: '**', redirectTo: '/404', pathMatch: 'full'}

Now create the service file and name it repository.service.ts. Place it in the same folder in which the environment service resides. In this service, we are going to create GET, POST, PUT, and DELETE requests.

So let's modify repository service:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { EnvironmentUrlService } from './environment-url.service';
import { HttpErrorResponse } from '@angular/common/http/src/response';

export class RepositoryService {

  constructor(private http: HttpClient, private envUrl: EnvironmentUrlService) { }

  public getData(route: string) {
    return this.http.get(this.createCompleteRoute(route, this.envUrl.urlAddress));

  public create(route: string, body) {
    return this.http.post(this.createCompleteRoute(route, this.envUrl.urlAddress), body, this.generateHeaders());

  public update(route: string, body){
    return this.http.put(this.createCompleteRoute(route, this.envUrl.urlAddress), body, this.generateHeaders());

  public delete(route: string){
    return this.http.delete(this.createCompleteRoute(route, this.envUrl.urlAddress));

  private createCompleteRoute(route: string, envAddress: string) {
    return `${envAddress}/${route}`;

  private generateHeaders() {
    return {
      headers: new HttpHeaders({'Content-Type': 'application/json'})

Repository Code Explanation


Let's explain this code.

First, we are injecting the HttpClient and the environment variable into the constructor. Then we are creating functions which are going to wrap our requests. The function getData is a wrapper for all GET requests. It accepts the route parameter of type string (api/owner or api/owner/id ...) and then combines it with the environment variable (localhost or www...). After all of that, we are going to have a route like, http://localhost:5000/api/owner,if it is a development environment, which perfectly fits our requirements on the server side.

The second function, create, is a wrapper for POST requests. It also generates a route, but additionally receives a body (an entity which we are creating) and generates headers. For this example, we are just creating the Content-Type inside the header. But if we need additional values inside the header, we could just add another key-value pair inside the HttpHeaders object.

The function update is pretty much the same as the create function, except it sends a PUT request.

Lastly, the delete function is a wrapper for the DELETE request which accepts a route like, api/owner/id.

Subscription on the HTTP Calls

These wrapper functions need a subscription in order to work. In this post, we are only creating a repository with the HTTP calls. But as soon as we start creating our pages, we are going to use subscription.

For now, I am just going to show you one example of a subscription:

public result: any;

constructor(private repo: RepositoryService) { }

public consumeGetFromRepository() {
      .subscribe(res => {
        this.result = res;
      (error) => {

As you may notice, we are calling the function getData from the repository, but that function won't be executed until we call the subscribe function. By calling the subscribe function, we are going to execute the getData function. The result from the response is going to be stored in the parameter res.


Excellent, now we have our repository prepared and we are ready to create components, which we are going to use with these repository functions to show results in a browser.

By reading this post you've learned:

  • What the HttpClientModule is.
  • How to work with environment files in Angular.
  • What the Angular services are.
  • How to use HTTP requests.
  • The way to subscribe to HTTP requests.

Thank you for reading the post, hopefully, it was helpful to you.

In the next part of the series, I am going to show you how to use lazy content loading in Angular. Moreover, we are going to show the resulting data on a page.

For any suggestions or questions, don't hesitate to leave the comment in the comment section below.

angular, http requests, web application development, web dev

Published at DZone with permission of Marinko Spasojevic . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}