AppDividend
Latest Code Tutorials

Angular 6 Tutorial With Example using Angular CLI

31,316

Get real time updates directly on you device, subscribe now.

Angular 6 Tutorial With Example using Angular CLI is the topic, we discuss today. Angular is One framework for Mobile & desktop. Angular puts you in control over scalability. Meet substantial data requirements by building data models on RxJS, Immutable.js or another push-model. We start this tutorial by installing Angular using Angular CLI and then working on our tutorial.

If you want to learn advance about Angular and Node.js then check out below course. This course has a brief introduction about Angular and Node.js and how they can work together. It is a complete practical example of Angular and Node.js. I also found it very useful. The Complete Angular, React & Node Guide Airbnb Style App

Angular 6 Tutorial

First, we need to set up a development environment.

Step 1: Set up the Development Environment.

Install Node.js® and npm if they are not already on your machine.

Then install the Angular CLI globally.

# run in administrator mode

sudo npm install -g @angular/cli

# or

yarn add global @angular/cli

The Angular CLI installs the necessary npm packages, creates the project files, and populates the project with a simple default app. Installation can take some time.

Now, create a boilerplate project using the following command.

ng new ngtutorial

Angular 6 Tutorial With Example using Angular CLI

So, now the project is initialized. Go into our project folder. 
cd ngtutorial

Open the project in your editor; I am using VSCode.

code .

Also, start the development server by the following command.

ng serve

Angular 6 Example

Step 2: Install Bootstrap 4 in an Angular app.

Go to your root and install bootstrap 4 using the following command.

yarn add bootstrap

Okay, now copy the bootstrap.min.css file from node_modules/bootstrap/dist/css folder to src/assets/css folder. If the CSS folder is not there, then create one and add that bootstrap.min.css file in it. Now, add the link to that CSS file inside src  >> index.html file.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Ngtutorial</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="/assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
  <app-root></app-root>
</body>
</html>

Now, you have successfully integrated the Bootstrap 4 Framework.

Step 3: Configure Routing for our components.

Now, create two components using the following command.

ng g c dashboard

Moreover, create another component.

ng g c users

Angular automatically update the app.module.ts file.

Now, Angular is Framework and not just library. So it has Router and Http module already included.

So, first, we will integrate routing for our application.

Related Posts
1 of 16

I am writing the whole code inside app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { UsersComponent } from './users/users.component';

const routes: Routes = [
  { path: 'users', component: UsersComponent },
  { path: 'dashboard', component: DashboardComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
    UsersComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  exports: [
    RouterModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

First, we have included the RouterModule and Routes module.

Next, we have created the routes array which is the type of Routes.

That array contains an object, and the properties are following.

  1. path
  2. component

Add an @NgModule.exports array with inRouterModule it. Exporting RouterModule makes router directives available for use in the components AppModule that will need them.

Okay, now we need to display the output of the different routes. For that, we need to define a <router-outlet> component. Also, we need to create a navbar, so that we can easily navigate to different routes and associated components. So, inside app.component.html file, add the following code. It is root component of our Angular application.

<!--The content below is only a placeholder and can be replaced.-->
<div id="app">
    <nav class="navbar navbar-expand-sm bg-light">
        <ul class="navbar-nav">
        <li class="nav-item">
            <a routerLink="/" class="nav-link">Home</a>
        </li>
        <li class="nav-item">
            <a routerLink="/dashboard" class="nav-link">Dashboard</a>
        </li>
        <li class="nav-item">
            <a routerLink="/users" class="nav-link">Users</a>
        </li>
        </ul>
    </nav>
    <div class="container">
        <router-outlet></router-outlet>
    </div>
</div>

Save the file and open the browser and go to http://localhost:4200/

You can see that we have now routing functionality.

Step 4: Create a JSON server that serves the data.

We need the fake data to work with that is why I am using one package called json-server for this tutorial. Okay, so let us install the package using Yarn package manager.

yarn global add json-server

# or

npm install -g json-server

Now we need to create a folder inside src directory called data and in that folder, create one file called db.json. Let us add the following data inside a db.json file.

{
    "results": [
    {
        "id": "1",
        "name": "RDJ",
        "movies": "100"
    },
    {
        "id": "2",
        "name": "Tom Holland",
        "movies": "3"
    },
    {
        "id": "3",
        "name": "Benedict Cumberbatch",
        "movies": "10"
    },
    {
        "id": "4",
        "name": "Chris Hemsworth",
        "movies": "30"
    },
    {
        "id": "5",
        "name": "Chris Evans",
        "movies": "20"
    }]
}

Now, start the JSON server using the following command.

json-server --watch src/data/db.json --port 4000

Now, we have a server running that can feed the data to our Angular Application.

Our JSON server is started at port: 4000 and URL is: http://localhost:4000/results

Step 5: Setup HttpClient.

In other Frontend libraries like React and Vue, we need to install third-party network request library like Axios. However, it is not the case in Angular. Angular is full fledge Frontend Framework, so it has already HTTP module. So first let us configure inside app.module.ts file.

// app.module.ts

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

 imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    HttpClientModule,
],

Now, inside users folder, create one file called User.ts. It is an interface, which tells the Angular application that, which kind of data is on the backend that we need to display at frontend.

// User.ts

export interface User {
    id: Number;
    name: String;
    movies: Number;
  }

Also, inside users folder, create one file called user.service.ts. We are writing the network request code inside this file. Then we import this file inside user.component.ts file and then call service file’s function.

// user.service.ts

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

@Injectable()
export class UserService {
  constructor(private http: HttpClient) { }
  url = 'http://localhost:4000';
  getUsers() {
    return this
            .http
            .get(`${this.url}/results`);
        }
}

Now, include this file inside users.component.ts file.

// users.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
import { User } from './User';

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

  users: User[];

  constructor(private userService: UserService) { }

  ngOnInit() {
    this.userService
      .getUsers()
      .subscribe((data: User[]) => {
          this.users = data;
        });
  }

}

Loop through that data and display it as a table inside the users.component.html file.

<table class="table table-striped">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Movies</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of users">
      <td>{{ user.id }}</td>
      <td>{{ user.name }}</td>
      <td>{{ user.movies }}</td>
    </tr>
  </tbody>
</table>

 

Angular HTTP Get request tutorial

So, in this simple tutorial, we have seen the following concepts.

  1. Angular 6 Routing
  2. Angular 6 HTTP Get Request
  3. Angular 6 Service Example

Finally, Angular 6 Tutorial With Example using Angular CLI is over. Thanks for taking this example.

24 Comments
  1. Rustem says

    core.js:1449 ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[UsersComponent -> UserService]:
    StaticInjectorError(Platform: core)[UsersComponent -> UserService]:
    NullInjectorError: No provider for UserService!
    Error: StaticInjectorError(AppModule)[UsersComponent -> UserService]:
    StaticInjectorError(Platform: core)[UsersComponent -> UserService]:
    NullInjectorError: No provider for UserService!

    1. Nemanja says

      Please include in your code!

      app.module.ts :

      import { UserService } from ‘./users/user.service’;

      @NgModule({

      providers: [UserService],

      })
      export class AppModule { }

      1. Derek says

        Thanks this worked for me.

      2. Bill says

        I could not get this to work at all until I tried Nemanja’s fix. Then it worked perfectly. A bit disappointing that the tutorial itself has not been corrected. However, I should thank Krunal for making the effort.

      3. User says

        That worked for me also. Thanks

      4. User says

        That worked for me also. Thanks

      5. Kalpana Suraj Prajapati says

        Thanks it worked for me too

      6. Osama says

        Thanks it worked for me as well

    2. Shailesh says

      You can also try this in your user.service.ts:
      @Injectable({
      providedIn: ‘root’
      })

      instead of this line: @Injectable({})

  2. jr says

    Git in project ?

  3. AKM says

    In user service,
    return this
    .http
    .get(`${this.url}/results`);
    gives 404 error

    1. Krunal says

      Please start your json server.

  4. Juan says

    In UserService i got this error:

    [ts] ‘UserService’ is declared but its value is never read.

  5. vince says

    doesnt work…
    thx for the effort but please provide the full code at the end in git repo

  6. Rishav Sumsail says

    Can you tell me difference between angular and ajax. Why ajax is not used now days.

  7. Kobe Bryant says

    ajax it’s just the same

  8. Rama says

    can you please mention more details about “Add an @NgModule.exports array with inRouterModule it” .
    Please mention file name, how to add @NgModule.exports array

  9. Wind Bearer says

    This tutorial was perfect for me, except for the one correction Nemanja suggested. It would be great if you would update the tutorial with the additional code. Thanks!!

  10. Pramod says

    Simple yet Great. Thanks Buddy..

  11. Chip Clark says

    I’m getting an error

    Failed to compile.

    ./src/app/app.module.ts 20:0
    Module parse failed: Unexpected token (20:0)
    You may need an appropriate loader to handle this file type.
    | HttpClientModule,
    | ],
    > ;
    | var routes = [
    | { path: ‘users’, component: UsersComponent },

  12. Chip Clark says

    Failed to compile.

    ./src/app/app.module.ts 20:0
    Module parse failed: Unexpected token (20:0)
    You may need an appropriate loader to handle this file type.
    | HttpClientModule,
    | ],
    > ;
    | var routes = [
    | { path: ‘users’, component: UsersComponent },

  13. Chip M Clark says

    Error:

    Failed to compile.

    ./src/app/app.module.ts 20:0
    Module parse failed: Unexpected token (20:0)
    You may need an appropriate loader to handle this file type.
    | HttpClientModule,
    | ],
    > ;
    | var routes = [
    | { path: ‘users’, component: UsersComponent },

  14. Chip Clark says

    In the users.compenents.ts file: When I include
    constructor(private userService: UserService) { }

    nothing from users.compenent.html shows up in on the user page.

    if I use constructor() {} the table shows up but no data

    In the app.module.ts
    if I include:
    imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    HttpClientModule,
    ],

    I get the following error:

    Failed to compile.

    ./src/app/app.module.ts 20:0
    Module parse failed: Unexpected token (20:0)
    You may need an appropriate loader to handle this file type.
    | HttpClientModule,
    | ],
    > ;
    | var routes = [
    | { path: ‘users’, component: UsersComponent },

  15. Chip Clark says

    Delete the last queries – fixed the issue

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.