Integrate Angular 8/9 with Node.js in MEAN Stack

Posted at: March 13, 2020 2:21 PM

In this lesson we will learn, how to work Angular 8/9 with NodeJS? In previous lesson we had learnt MEAN Stack with MySQL and this lesson we had created nodejs app.

Now we will create Angular application and connect with NodeJS.

Create Angular Application

Before create angular appliction must be sure intalled angular-cli in your system. If no then install angular-cli using below command

Install the Angular CLI


npm install -g @angular/cli

Create new application


ng new meanapp

Press "y" for create routing module and press Enter key.


? Would you like to generate a routing module? (y/N)y

Select stylesheet format for this application and press Enter key. If you want another stylesheet format then you can select format by press up-down arrow key.


  ? Which stylesheet format would you like to use? CSS
  CSS
  SCSS   [ http://sass-lang.com   ]
  SASS   [ http://sass-lang.com   ]
  LESS   [ http://lesscss.org     ]
  Stylus [ http://stylus-lang.com ]

Load application directory "meanapp" and run application.


 cd meanapp
 ng serve --open

Create Components and Services

Now stop the Angular application by pressing ctrl + c and create components and services.

Create users and 404 page component


ng generate component users
ng generate component message
ng generate component page-not-found

Create users service into services folder.


ng generate service services/users

Edit file src/app/app.component.html


<h1>Connect Angular with Nodejs</h1>
<router-outlet></router-outlet>

Routing

Edit file src/app/app.routing.module.ts


import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { UsersComponent } from './users/users.component';

const routes: Routes = [
  { path: '', redirectTo: '', pathMatch: 'full' },
  { path: 'users', component: UsersComponent },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Services

Create two service files src/app/services/message.service.ts and src/app/services/http-error-handler.service.ts for showing http error messages.

message.service.ts


import { Injectable } from '@angular/core';

@Injectable()
export class MessageService {
  messages: string[] = [];

  add(message: string) {
    this.messages.push(message);
  }

  clear() {
    this.messages = [];
  }
}

http-error-handler.service.ts


import { Injectable } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';

import { Observable, of } from 'rxjs';

import { MessageService } from './message.service';

/** Type of the handleError function returned by HttpErrorHandler.createHandleError */
export type HandleError =
  <T> (operation?: string, result?: T) => (error: HttpErrorResponse) => Observable<T>;

/** Handles HttpClient errors */
@Injectable()
export class HttpErrorHandler {
  constructor(private messageService: MessageService) { }

  /** Create curried handleError function that already knows the service name */
  createHandleError = (serviceName = '') => <T>
    (operation = 'operation', result = {} as T) => this.handleError(serviceName, operation, result);

  /**
   * Returns a function that handles Http operation failures.
   * This error handler lets the app continue to run as if no error occurred.
   * @param serviceName = name of the data service that attempted the operation
   * @param operation - name of the operation that failed
   * @param result - optional value to return as the observable result
   */
  handleError<T> (serviceName = '', operation = 'operation', result = {} as T) {

    return (error: HttpErrorResponse): Observable<T> => {
      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      const message = (error.error instanceof ErrorEvent) ?
        error.error.message :
       `server returned code ${error.status} with body "${error.error}"`;

      // TODO: better job of transforming error for user consumption
      this.messageService.add(`${serviceName}: ${operation} failed: ${message}`);

      // Let the app keep running by returning a safe result.
      return of( result );
    };

  }
}

app.module.ts

Edit src/app/app.module.ts for import HttpClientModule, HttpErrorHandler and MessageService. And add service HttpErrorHandler and MessageService providers to the application dependency injectors.

Why import HttpClientModule?

For http service use HttpClient. HttpClient is Angular's mechanism for communicating with a remote server over HTTP. HttpClient available everywhere in the your app to import HttpClientModule in app.module.ts


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpErrorHandler } from './services/http-error-handler.service';
import { MessageService } from './services/message.service';
import { MessageComponent } from './message/message.component';
import { UsersComponent } from './users/users.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';

@NgModule({
  declarations: [
    AppComponent,
    MessageComponent,
    UsersComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule
  ],
  providers: [
    HttpErrorHandler,
    MessageService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Set varialble in environments

Edit file src/environments/environment.ts and src/environments/environment.prod.ts for set variable of api base url for development and production mode of your application.

src/environments/environment.ts


export const environment = {
  production: false,
  apiUrl: 'http://localhost:3000'
};

src/environments/environment.prod.ts


export const environment = {
  production: true,
  apiUrl: 'http://yourdomain.com:3000'
};

User Service

Edit file src/app/services/users.service.ts for connect nodejs api. In this service I have used http.get method for fetch users.


import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { HttpErrorHandler, HandleError } from './http-error-handler.service';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class UsersService {

  private apiUrl = `${environment.apiUrl}/users`;
  private handleError: HandleError;

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };

  constructor(
    private http: HttpClient,
    private httpErrorHandler: HttpErrorHandler
  ) {
    this.handleError = this.httpErrorHandler.createHandleError('UsersService')
  }

  getUsers() {
    return this.http.get(`${this.apiUrl}`)
    .pipe(
      catchError(this.handleError('getUsers', null))
    )
  }
}

Message Component

Edit file src/app/message/message.component.ts and import MessageService for showing messages.


import { Component, OnInit } from '@angular/core';
import { MessageService } from '../services/message.service';

@Component({
  selector: 'app-message',
  templateUrl: './message.component.html',
  styleUrls: ['./message.component.css']
})
export class MessageComponent implements OnInit {

  constructor(
    public messageService: MessageService
  ) { }

  ngOnInit() {
  }

}

src/app/message/message.component.html


<div *ngIf="messageService.messages.length">
  <h3>Messages</h3>
  <button class="clear" (click)="messageService.clear()">clear</button>
  <br>
  <ol>
    <li *ngFor='let message of messageService.messages'> {{message}} </li>
  </ol>
</div>

Users Component

Edit file src/app/users/users.component.ts and import UserService


import { Component, OnInit } from '@angular/core';
import { UsersService } from '../services/users.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {

  users: any;

  constructor(
    private usersService: UsersService
  ) { }

  ngOnInit() {
    this.getUsers();
  }

  getUsers() {
    this.usersService.getUsers().subscribe(
      result => {
        this.users = result;
      },
      err => console.log(err)
    )
  }

}

Edit file src/app/users/users.component.html


<h2>Users</h2>
{{users | json}}

Changes in NodeJS

Edit file routes/users.js


var express = require('express');
var router = express.Router();
var db = require("../db");

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.json({name: 'Aayansh'});
});

module.exports = router;

Conclusion

In this lesson we have created application in Angular 8/9 and use services, routing, providers and http error handlers for showing http error messages etc. And connect Angular application with Node.JS. Next lesson we will learn user registration in MEAN application.

This lesson also available on YouTube
integrate angular 8/9 with nodejs angular 8/9 with nodejs angular 8/9 connect to rest api angular 8/9 connect to mysql run angular app with node angular 8/9 and node js integration angular 8/9 with node js example

Please leave comments

0 Comments