Creating My First ChatBot Using Angular(5.0) And Dialogflow (API.AI)

First, let me tell you why you should require Chat Bots; is it really helpful; and who are building bots etc.

Anyone who has ever tried to contact a company through customer care center might know how slow and frustrating process it is. You remember that audio tape “press 1 for this, press 2 for this, press * to go back to the menu, and blah blah blah….“?

Say, for example, if you want to activate a simple caller tune to your phone number, you have to spend at least 10 minutes to know the code to activate that caller tune, by hearing that audio tape and pressing so many numbers. And finally, if you had a good luck, then only you are able to activate your caller tune.

However, there is a great solution to this kind of problem, which is faster than the customer care center - the Chat Bots. Nowadays, Chat Bots can be made using AI also, so it doesn’t limit them.

"A chatbot is a service, powered by rules and sometimes artificial intelligence that you interact with via a chat interface."

According to some people, Bots will completely kill the web and mobile apps. The main reasons for that are -

  • Bots are faster than the website and mobile apps, they replied instantly.
  • Mobile apps need to download and it occupies some memory of your phone whereas the bot doesn’t need to download it lives within your messenger only.
  • It is easier to use Bots and many more.

Messaging is the new browser and bots are the new apps.


  • JavaScript
  • Angular-CLI
  • Dialogflow account (previously API.AI)
  • Visual Studio Code (optional)

Setting Up Dialogflow

  • Navigate to Dialogflow and log in to your account.

  • Then, press "Create Agent" to create your first agent.

  • After filling the required details, press "Create".

  • Then, press the "Create Intent" button to create your first intent. Intents are usually user’s intention of asking questions. Dialogflow extracts the user intention from text using Natural Language Processing.
    • Add you intent/question in “user says” field, as shown below.


    • And, the answer should be in response field, as shown below.
  • The entire page will look like the following.

  • Now, you can also test your sentence in the console.


So far, we have created our Dialogflow Agent and Intent. Now, it’s time to create an Angular application to create a user interface and integrate our Dialogflow Agent to Angular.

Angular Application


  • You can create an Angular project using Angular-CLI.
    1. ng new ngbotdemo    


  • Integrate Dialogflow JavaScript SDK in our Angular project using the following command.
    1. npm install api-ai-javascript  - - save-dev  
  • Store the Client access token from Dialogflow to your app inside environment.ts file, as shown below.


Now, store the client access token in environment.ts file.

  1. export const environment = {  
  2.  production: false,  
  3.  dialogflow: {  
  4.    angularBot: 'your-key'  
  5.  }  
  6. ;  

Now, let us create the service using the following command.

  1. ng g s chat  


Inside the chat service, we will first import the following packages.

  1. import { environment } from '../../environments/environment';  
  2. import { ApiAiClient } from 'api-ai-javascript';  
  3. import { Observable } from 'rxjs/Observable';  
  4. import { BehaviorSubject } from 'rxjs/BehaviorSubject';  

Then, we will create one message class inside the service, which has two members - msg (which will be used to store the content or message send by the user or bot) and from (which will be used to store the info of who sent that message, i.e., either ‘user’ or ‘Bot’).

  1. export class Message {  
  2.   constructor(public msg: string, public from: string) { }  
  3. }  


  • Now, let us create the instance of API.AI client – the JavaScript SDK for Dialogflow, and then, pass the client access token to that instance of API.AI client.


  1. readonly token = environment.dialogflow.angularBot;  
  2. readonly _client = new ApiAiClient({ accessToken: this.token });  

Now, it’s time to create a method that will interact with our bot, i.e., send and receive messages, as shown below.

  1. talk(msg: string) {  
  2.   const userMessage = new Message(msg, 'user');  
  3.   this.update(userMessage);  
  4.   return this._client.textRequest(msg)  
  5.     .then(res => {  
  6.       const speech = res.result.fulfillment.speech;  
  7.       const botMessage = new Message(speech, 'bot');  
  8.       this.update(botMessage);  
  9.     });  
  10. }  

The full chat.service.ts will look like below.

  1. import { Injectable } from '@angular/core';  
  2. import { environment } from '../../environments/environment';  
  3. import { ApiAiClient } from 'api-ai-javascript';  
  4. import { Observable } from 'rxjs/Observable';  
  5. import { BehaviorSubject } from 'rxjs/BehaviorSubject';  
  7. export class Message {  
  8.   constructor(public msg: string, public from: string) { }  
  9. }  
  11. @Injectable()  
  12. export class ChatService {  
  13.   readonly token = environment.dialogflow.angularBot;  
  14.   readonly _client = new ApiAiClient({ accessToken: this.token });  
  15.   conversation = new BehaviorSubject<Message[]>([]);  
  16.   constructor() { }  
  17.   // Sends and receives messages via DialogFlow  
  18.   talk(msg: string) {  
  19.     const userMessage = new Message(msg, 'user');  
  20.     this.update(userMessage);  
  21.     return this._client.textRequest(msg)  
  22.       .then(res => {  
  23.         const speech = res.result.fulfillment.speech;  
  24.         const botMessage = new Message(speech, 'bot');  
  25.         this.update(botMessage);  
  26.       });  
  27.   }  
  28.   // Adds message to source  
  29.   update(msg: Message) {  
  31.   }  
  33. }  

Now, finally, it’s time to create our user interface, i.e., chat-component and call talk method from chat.service.

Use this command to create a new component.

  1. ng g c chatcompoent   

Your chat.component.ts file look like following.

  1. import { Component, OnInit, ViewEncapsulation } from '@angular/core';  
  2. import { ChatService, Message } from '../chat.service';  
  3. import { Observable } from 'rxjs/Observable';  
  4. import 'rxjs/add/operator/scan';  
  6. @Component({  
  7.   selector: 'chat-component',  
  8.   templateUrl: './ 'chat-component.component.html',  
  9.   styleUrls: ['./ 'chat-component.component.css'],  
  10.   encapsulation: ViewEncapsulation.None  
  11. })  
  12. export class Chat-ComponentComponent implements OnInit {  
  13.   messages: Observable<Message[]>;  
  14.   strMsg: string;  
  15.   constructor(private chat: ChatService) { }  
  16.   ngOnInit() {  
  17.     this.messages =  
  18.       .scan((acc, val) => acc.concat(val));  
  19.   }  
  20.   sendMessage() {  
  22.     this.strMsg = '';  
  23.   }  
  24. }  

Here, I am injecting the chat-service inside the constructor. And calling my talk method when a user presses the Enter key or the Send button. I have used two-way binding to get the input from the input-box. For that, I have created the variable strMSg.

My chat-component.html will look like this.

  1. <h1>My First ChatBot using Angular and Dialogflow</h1>  
  2. <ng-container *ngFor="let m of messages | async">  
  3.   <div class="message" [ngClass]="{ 'from': m.from === 'bot',  
  4.                                     'to':   m.from === 'user' }">  
  5.     {{ m.msg }}  
  6.   </div>  
  7. </ng-container>  
  8. <label for="nameField">Your Message</label>  
  9.    <input [(ngModel)]="strMsg" (keyup.enter)="sendMessage()" type="text">  
  10.    <br>  
  11. <button (click)="sendMessage()">Send</button>  



Similar Articles