Angular
This guide helps you add the TalkJS inbox chat UI to your Angular app.
To get started, create a TalkJS account or login to your dashboard. You can get your app ID from the Settings page of the dashboard.
Add TalkJS to your project by installing it.
1npm install talkjs --save
First, create a service that contains TalkJS methods. This make it easier to reuse these methods in any part of your application.
1ng generate service talk
Next, import TalkJS into the service you just created. Add the following code in the talk.service.ts
file.
1import Talk from 'talkjs';
You also want to declare a variable for the current user in the service. This way all methods can have access to it.
1export class TalkService {2 private currentUser: Talk.User;3}
In the service, add methods that will do the following:
- Create a TalkJS user
- Create a TalkJS session
- Get or create a TalkJS conversation
- Create the Inbox
Start with the first.
The first step is to create a TalkJS user. The Talk.User object is used to synchronize user data with TalkJS, so you can display it inside the chat UI. Add a method to the service that maps a user object from your app to a Talk.User:
1async createUser(applicationUser: any) {2 await Talk.ready;3 return new Talk.User({4 id: applicationUser.id,5 name: applicationUser.username,6 photoUrl: applicationUser.photoUrl,7 role: applicationUser.role8 });9 }
Be sure to change the applicationUser
type to your application's user type and edit the code accordingly.
A session represents a user's active browser tab. It also authenticates your app with TalkJS. To create a session, you need your app ID, which you can get from the Settings page of your TalkJS dashboard, and the current TalkJS user. Here you'll use a hard-coded value for the current user, but remember to change it to use the current user logged in to your application.
1async createCurrentSession() {2 await Talk.ready;3 const user = {4 id: 1,5 username: 'Alice',7 photoUrl: 'https://talkjs.com/images/avatar-1.jpg',8 welcomeMessage: 'Hey there! How are you? :-)',9 role: 'default'10 };11 this.currentUser = await this.createUser(user);12 const session = new Talk.Session({13 appId: 'YOUR_APP_ID',14 me: this.currentUser15 });16 return session;17 }
Remember to replace YOUR_APP_ID with the app ID found on the Settings page of your TalkJS dashboard.
Next, create a conversation. Use the getOrCreateConversation
method to get the conversation between the two users if the conversation already exists, or otherwise to create a new conversation.
1private async getOrCreateConversation(session: Talk.Session, otherApplicationUser: any) {2 const otherUser = await this.createUser(otherApplicationUser);3 const conversation = session.getOrCreateConversation(Talk.oneOnOneId(this.currentUser, otherUser));4 conversation.setParticipant(this.currentUser);5 conversation.setParticipant(otherUser);6 return conversation;7 }
The Talk.oneOnOneId
method computes a conversation ID based on participants' IDs. Use this method if you want to create a conversation between only two users. You may want to create a group conversation or generate a conversation ID associated with a transaction that happened on your platform, for example a purchase. You can find how to do that in the documentation of the conversation ID.
The inbox is one of the UI types of TalkJS. It shows a user's conversation history and it allows them to write messages. To create the inbox, add the following method. The method contains another hard-coded user to serve as the other application user.
1async createInbox(session: Talk.Session) {2 const otherApplicationUser = {3 id: 5,4 username: 'Lo',6 photoUrl: 'https://talkjs.com/images/avatar-5.jpg',7 welcomeMessage: 'Hey, how can I help?',8 role: 'default'9 };1011 const conversation = await this.getOrCreateConversation(session, otherApplicationUser);12 const inbox = session.createInbox();13 inbox.select(conversation);14 return inbox;15 }
Now you can import the service you just created in any component and use the methods.
For this section, you'll use the talk service in the app
component. Remember that you can repeat these steps in any component.
In the HTML file of the component app.component.html
, add the element you want to mount the inbox on.
1<div #talkjsContainer style="height: 500px">Loading...</div>
The #talkjsContainer
lets you refer to the element in your component code.
Next, import the Talk Service you created into the component file app.component.ts
and initialize it in the constructor method. Also import OnInit
, ViewChild
and ElementRef
which you'll use in the component.
1import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';2import { TalkService } from 'src/app/talk.service';3import Talk from 'talkjs';45@Component({6 selector: 'app-root',7 templateUrl: './app.component.html',8 styleUrls: ['./app.component.css'],9})10export class AppComponent implements OnInit {11 private inbox: Talk.Inbox;12 private session: Talk.Session;1314 constructor(private talkService: TalkService) {}15}
First, add a view query to reference the element you added to the HTML file. In the app.component.ts
file, add the following:
1@ViewChild('talkjsContainer') talkjsContainer!: ElementRef;
Next, add a method to use the service methods you created earlier to create the inbox and mount it on the HTML element you added. Then call this method in the ngOnInit
lifecycle hook.
1ngOnInit() {2 this.createInbox();3 }45 private async createInbox() {6 const session = await this.talkService.createCurrentSession();7 this.inbox = await this.talkService.createInbox(session);8 this.inbox.mount(this.talkjsContainer.nativeElement);9 }
That's it. The inbox should now be running on your app. Here is the final result and the full code for this:
Select the result tab to see the Inbox. Go ahead, have a chat with Lo. He won't respond yet, but hey, it's a start! If you get an error, verify that appId
is correct.
You can find several examples for different use cases in Angular on the TalkJS examples repository on GitHub.
Next, you can learn how to add notifications.