How to build an Angular 8 application with API request in 10 minutes?
Tags: programming, angular, beginners, codenewbie
Published: 2019-12-02 16:12:31

---
canonical_url: https://www.blog.duomly.com/angular-tutorial/
---

Some time ago, I created the first tutorial about <a href="https://www.blog.duomly.com/how-to-create-react-app-in-5-minutes/">React.js</a> where I showed you how to create an easy React.js application using an existing API and Bootstrap for styling. The positive response for this article brought me to the idea of creating a series of simple tutorials on how to build an application with the most popular front-end frameworks. To make it even more helpful for beginners and those who prefer to watch and learn, then read and learn; I also decided to add a Youtube video to every episode. 

So, as I already mentioned before, I already created text and Youtube [LINK] tutorials about <a href="https://www.youtube.com/watch?v=SPM4xyYd9MI">React.js</a>. After this, I decided to follow with Vue.js, and this is how <a href="https://www.blog.duomly.com/vue-js-tutorial-how-to-create-vue-js-app-in-5-minutes/">Vue.js tutorial</a> and <a href="https://www.youtube.com/watch?v=i43MZ_oSRfs">Vue js tutorial - How to build application in Vue</a> were created. 

Today it came the time to create an article and Youtube episode for the Angular enthusiasts. So, make yourself comfortable, and let’s start with the framework created by Google developers.

{% youtube WYRLYw2rYj0 %}

Let’s start!

<h4>1. Install @angular/cli</h4>

This tutorial, we are going to start installing Angular CLI. This tool allows us to create a ready to use application with all the dependencies installed. What’s even greater, Angular CLI will allow us to create ready components and services. So, let’s open the console and use the following command:

```
npm install -g @angular/cli
```

After the installation is finished, you should see the information like below:

<a href="https://www.duomly.com">
![Duomly - Programming Online Courses](https://thepracticaldev.s3.amazonaws.com/i/d7cd29o1rpv21abt22hv.png)
</a>

<h4>2. Create a project</h4>

So, we already have the tool to build the application, and now we are going to create one. Navigate to the folder where you want to create your app and use the ng command. In my case, the name of the application is „albums”, but you can feel free to name your app as you prefer.

```
ng new albums
```

After running the command, you will be asked two questions. First, if you would like to install routing, and the second one, what styles do you prefer, CSS, Sass, Less, etc.

In this case, I selected yes to the first question, and I decided to have CSS for styling. 

After creating the project successfully, we are ready to run it. 

<h4>3. Run the app</h4>

To run the application, you need to get the app folder in the console first. In my case, it's albums. Then type the following command:

```
ng serve
```

It may take a few seconds, and after you see a message that it’s compiled successfully, you can check how it works in the browser.
The default port for Angular apps is 4200, but you can customize it if you wish.

Let’s go to the browser and open http://localhost:4200 or your custom port. You should see an application like on the image below:

<a href="https://www.duomly.com">
![Duomly - Programming Online Courses](https://thepracticaldev.s3.amazonaws.com/i/cdgdw6eo4zwwk8zhy0jq.png)
</a>

Great, the first step is done. Now, let’s get into building our app!

<h4>4. Create first component</h4>

Let’s open a folder with the application in your favorite code editor. Inside **./src/app** folder is our main files app.component.ts and app.module.ts. We want to create our own component right now, but to avoid a crazy mess in the structure of our application, let’s create a new folder called **components**.

<a href="https://www.duomly.com">
![Duomly - Programming Online Courses](https://thepracticaldev.s3.amazonaws.com/i/pqtq76cgvsouegng6lbq.png)
</a>

Great, if our folder is ready now, let’s navigate to this folder in your console, and we are going to use Angular CLI to generate the component. For this, we will use the following command:

```
ng generate component albums
```
And after a second, our component should be ready. Now, let’s get rid of what we have displayed currently and set the rout to our new component.

<h4>5. Setting the first route</h4>

Let’s start by removing almost everything from app.component.html file. The only thing we would like to leave there is < router-outlet ></router-outlet >, the file should look like this:

```html
<div class="container">
  <router-outlet></router-outlet>
</div>
```

If it’s ready, let’s go to the **app-routing.module.ts** to set the path for our Albums component. We have to add a new path like in the following code:


```javascript
const routes: Routes = [
  { path: '', component: AlbumsComponent },
];

```

After this step, we should see the template of Albums Component in the browser.

<a href="https://www.duomly.com">
![Duomly - Programming Online Courses](https://thepracticaldev.s3.amazonaws.com/i/me68k69vvrdhm8q4zn2k.png)
</a>

<h4>6. Creating service and API call</h4>

The next thing we would like to do is create an API call. In Angular, we use services to create an Http request, but we also need to import HttpClientModule from @angular/common/http in the **app.module.ts** file, and let’s inject it in the imports array.

```javascript
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 { AlbumsComponent } from './components/albums/albums.component';

@NgModule({
  declarations: [
    AppComponent,
    AlbumsComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
```
Now, let’s create a new folder called services inside **./src/app** to keep there our services. If you are ready with the services folder, you can generate new service just like components with the following command (remember to navigate to the folder where you would like your service to be created):

```
ng generate service <servicename>
```
In our case, let’s create a service called photos. When it’s ready, open photos.service.ts file and import HttpClient from @angular/common/http. When it’s done inject HttpClient in the constructor like in the code below:

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

@Injectable({
  providedIn: 'root'
})
export class PhotosService {
  constructor(
    private http: HttpClient
  ) { }
}
```

Finally, we can create our first API call. As in previous tutorials, I’m going to use www.jsonplaceholder.com API. Let’s create a function that makes an API request and returns it.

```javascript
 getAlbums() {
    return this.http.get('https://jsonplaceholder.typicode.com/albums');
  }
```

<h4>7. Call API from component</h4>

Let’s continue with calling the API for the data. In the albums.component.ts  let’s import the service and inject it to the component in the constructor. 

```javascript
import { PhotosService } from './../../services/photos.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-albums',
  templateUrl: './albums.component.html',
  styleUrls: ['./albums.component.css']
})
export class AlbumsComponent implements OnInit {
  constructor(
    private photosService: PhotosService,
  ) { }

  ngOnInit() {}
}

```
We also need to define a property for the **albums** in our component. Just above the constructor let’s add albums property. 

```javascript
export class AlbumsComponent implements OnInit {
  albums;
  constructor(
    private photosService: PhotosService,
  ) { }
```

Now, let’s assign the response from our API to the albums property in the ngOnInit() method. 

```javascript
ngOnInit() {
  this.albums = this.photosService.getAlbums();
}
```

<h4>8. Create a template</h4>

Now it’s time to display our data, and for that, we need a nice template. To make it easier and faster let’s import Bootstrap in the index.html file.

```html
<head>
  <meta charset="utf-8">
  <title>Albums</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
```

If it’s done, let’s open albums.component.html file and create a template like in the following code.

```html
<div>
  <h3>Albums collection</h3>
  <div class="row">
    <div class="col-sm-4" *ngFor="let album of albums | async">
      <div class="card">
        <div class="card-body">
          <a>{{album.title}}</a>
        </div>
      </div>
    </div>
  </div>
</div>
```
To add our data to the template we used *ngFor and async pipe. As you probably see, inside the code, there is an <a> element that will be redirecting to the particular album to display photos from this album. To achieve this we need to create another route.

<h4>9. Creating route with variable</h4>

Inside app-routing.module.ts file, we have to add another route object. In this case, the path will be a string with variable and we will redirect to a particular album by id. Please, update the code as in the example below. 

```javascript
const routes: Routes = [
  { path: '', component: AlbumsComponent },
  { path: 'photos/:albumId', component: PhotosComponent }
];
```

Now, you should receive an error, because we use a non-existing Photos Component in our path. In this case, we have to create a new component to remove the bug.

<h4>10. Create another component</h4>

Like before, let’s navigate to the components folder in the console and generate a new component named photos with ng command. If it’s ready your error should no longer be there.

<h4>11. Add redirect link</h4>

In the Albums component, we left our code unfinished. Let’s get back to the template and update the link as in the code below.

```html
  <a routerLink="photos/{{album.id}}">{{album.title}}</a>
```

Now, let’s apply some CSS code to our template in the albums.components.css file.

```css
h3 {
  margin-top: 5%;
  margin-bottom: 5%;
}

.card {
  margin-bottom: 3%;
}

.card:hover {
  background-color: #007bff;
}

.card:hover a {
  color: white;
}

.card a:hover {
  color: white;
  text-decoration: none;
}
```

Woohoo! The first part of the app is ready. Check out the result in the browser and you should see the app like in the image.

<a href="https://www.duomly.com">
![Duomly - Programming Online Courses](https://thepracticaldev.s3.amazonaws.com/i/0jgbmizh54yrgluy8wqw.png)
</a>

<h4>12. Create a second API call</h4>
 
Now we need to start from getting data by album id to our new component. Let’s go back to the **photos.service.ts** file and create another function.

```javascript
  getPhotos(albumId) {
    return this.http.get(`https://jsonplaceholder.typicode.com/photos?albumId=${albumId}`);
  }
```

<h4>13. Get query param from the link</h4>

If it’s ready we can use it inside the Photos Component. So, open photos.component.ts file and import Photos Service there as previously in Albums Component and inject it the same way.

```javascript
import { PhotosService } from './../../services/photos.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-photos',
  templateUrl: './photos.component.html',
  styleUrls: ['./photos.component.css']
})
export class PhotosComponent implements OnInit {
  photos;
  constructor(
    private photosService: PhotosService,
  ) { }

```

Now, we will call getPhotos() function in the ngOnInit() method, but don’t forget to initialize the photos' property above the constructor. 

```javascript
ngOnInit() {
  this.photos = this.photosService.getPhotos(albumId);
}
```

In this step, we clearly need an album id which we can get from the query params in the link. To get access to the params we need to install ActivatedRoute from @angular/router and this we also need to inject in the constructor. 

When it’s ready we can initialize another property albumId below the photos property. In the ngOnInit() method let’s assign the id from the URL to this.albumId and let’s pass it to the API URL.

```javascript
import { PhotosService } from './../../services/photos.service';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-photos',
  templateUrl: './photos.component.html',
  styleUrls: ['./photos.component.css']
})
export class PhotosComponent implements OnInit {
  photos;
  albumId;
  constructor(
    private photosService: PhotosService,
    private route: ActivatedRoute,
  ) { }

  ngOnInit() {
    this.albumId = this.route.snapshot.params.albumId;
    this.photos = this.photosService.getPhotos(this.albumId);
  }
}
```

We are almost there, the only thing we need to do right now is to create a template for the photos. 

<h4>14. Create a template</h4>

Inside the photos.component.html file let’s add the following HTML code and pass photos with *ngFor.

Here we will also pass this.albumId to display the id of the album. 

```html
<div>
  <button routerLink="/" class="btn btn-light">Go back</button>
  <h3>Album {{albumId}}</h3>
  <div class="row">
    <div class="col-md-3 photo" *ngFor="let photo of photos | async">
      <img src={{photo.url}} class="img-fluid" />
    </div>
  </div>
</div>
```

The last step is to add some CSS code to make our app pretty. 

```CSS
.photo {
  margin-bottom: 3%;
}
h3 {
  margin-bottom: 5%;
  margin-top: 5%;
}
button {
  margin-top: 10px;
}
```

<h4>15. Woohoo!</h4>

We are there! Check your app in the browser and try to navigate to the albums and come back. You should be able to see the screens like in the images below.

<a href="https://www.duomly.com">
![Duomly - Programming Online Courses](https://thepracticaldev.s3.amazonaws.com/i/0jgbmizh54yrgluy8wqw.png)
</a>
Albums page

<a href="https://www.duomly.com">
![Duomly - Programming Online Courses](https://thepracticaldev.s3.amazonaws.com/i/g9za8y9gc9a95fh3s9bo.png)
</a>
Photos page


Congratulations!

<h4>Conclusion</h4>

In this article, I’ve created a simple application using Angular 8. To create the app, components, and service I user Angular CLI tool, and we used Bootstrap to make our templates nice and fast. Application has a simple routing to make you familiar with creating routes and REST API request to show you how we manage API calls in Angular. As a result, I got an app with a listing of albums and details page for each of them.

I hope you will find this tutorial helpful and use it as a base for your first Angular application training. If you feel more comfortable with Youtube videos feel free to watch this tutorial here.

Have a nice coding,
Anna from Duomly

<a href="https://www.duomly.com">
![Duomly - Programming Online Courses](https://thepracticaldev.s3.amazonaws.com/i/fwh5gaq7flxdfr0xot2y.png)
</a>
This article was originally published at: https://www.blog.duomly.com/angular-tutorial/