How To Make Asynchronous Calls In Angular 4

How To Make Asynchronous Calls In Angular 4

In this tutorial you’ll learn about two important aspects of making asynchronous calls in Angular 4. You’ll learn about how to return response from an Angular service and how to receive response from an Angular service.

Other tutorials in the Angular 4 Web Series:

Creating An Angular App

Generate a new Angular project using the Angular command.


ng new angular-app

Navigate to the project folder and install the required dependencies.


cd angular-app
npm install

Once all dependencies are installed, start the server and you should have the default application at http://localhost:4200/.

Writing An Angular Component

Let’s start by creating an Angular component called test. Create a folder test inside the src/app folder. Inside the test folder create a file called test.component.ts. Add the following code to the test.component.ts file:


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

@Component({
    selector: 'test',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.css']
})
export class TestComponent {
    constructor(){
        
    }
}

Writing An Angular Service

Next you need an Angular service to make a call from the Angular component. Create a file called test.service.ts and add the following code:


import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class TestService {
    url: string
    constructor(private http: Http) {
        
    }

    search_word(term) {
        
    }
}

Returning Response from Angular Service

Inside the search_word method you’ll make a call to an API URL. For this tutorial you’ll make use of the Datamuse API. The Datamuse API returns similar words as per the query keyword.


https://api.datamuse.com/words?ml=

You’ll make use of the Http module provided by Angular to make the GET request to the Datamuse API.

http.get returns an observable. Let’s use http.get to query the API. Here is how the search_word function looks:


search_word(term) {
    return this.http.get(this.url + term).map(res => {
        return res.json().map(item => {
            return item.word
        })
    })
}

Receiving Response from Angular Service

To receive response from the search_word method, you need to import the service in the test.component.ts.


import { TestService } from './test.service';

Add the TestService as providers to the component.


@Component({
    selector: 'test',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.css'],
    providers: [TestService]
})

Initialize the TestService in the TestComponent’s constructor method.


constructor(private testService: TestService){
    
}

Subscribe to the search_word method from TestService. Here is the modified test.component.ts file:


import { Component } from '@angular/core';
import { TestService } from './test.service';
import { Observable } from 'rxjs/Rx';

@Component({
    selector: 'test',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.css'],
    providers: [TestService]
})
export class TestComponent {
    constructor(private testService: TestService){
        this.testService.search_word('hello').subscribe(res => {
            console.log('Response received is ', res);
        })
    }
}

Modify the app.module.ts file to bootstrap the TestComponent instead of AppComponent.


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component'

@NgModule({
  declarations: [
    AppComponent,
    TestComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [TestComponent]
})
export class AppModule { }

Modify the src/index.html page to show the TestComponent.


<body>
     <test></test>
</body>

Save the above changes and restart the server using ng serve. Check the browser console and you should be able to see the API call result.

Wrapping It Up

In this tutorial, you saw how to make asynchronous calls in Angular 4. You used the Http module to make asynchronous calls in Angular 4. You saw how to subscribe to an observable.

Source code from this tutorial is available on GitHub.

Do let us know your thoughts and suggestions in the comments below.