// Connect by providing user id only
this.chatService.init("<API key>", "<user id>", "<token or provider>");
// Or connect by providing user settings such as name, image, etc.
this.chatService.init(
"<API key>",
{
id: "<user id>",
name: "Sara",
image: "url/to/image",
},
"<token or provider>"
);
// Guest users
this.chatService.init(environment.apiKey, "john", "guest");
// Anonymous users
this.chatService.init(environment.apiKey, undefined, "anonymous");
Users and tokens
Connecting users
The client documentation details all important information about regular and authless users. Here is how you can connect these users in the Angular SDK:
Generating tokens
Regular users (all users except guests and anonymous users) require a valid JWT token to access the Stream API. Tokens can’t be created securely on the client-side, so you should generate tokens on your server-side. All important information about tokens can be found in the client documentation.
Here is how you can provide the generated token to the Angular SDK:
// Option 1: using a static token
this.chatService.init(
"<API key>",
"<user or id>",
// Example static token
"eyJhbGcIOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
);
// Option 2. using a token provider
this.chatService.init(
"<API key>",
"<user or id>",
// Example token provider
// The SDK will call your token provider when you connect, or when the token is expired and it needs a new one
// With token providers you can use short-living tokens, so we advise using this method in your production applications
() => async {
const token = await (<HTTP call to your own backend to obtain a new token>).token;
return token;
}
);
This is how you can use developer tokens with the Angular SDK:
import { StreamChat } from "stream-chat";
const apiKey = "<API key>";
const userId = "<user id>";
const devToken = StreamChat.getInstance(apiKey).devToken(userId);
this.chatService.init(apiKey, userId, devToken);
Disconnecting users
If your application allows connecting with different users, you should make sure to properly disconnect the previous user before connecting a new one:
private async connectUser(userId: string) {
// Make sure to wait for disconnect before connecting a new user
await this.disconnectUser();
await this.chatService.init('<API key>', userId, '<token provider>');
this.channelService.init('<channel filters>');
}
private async disconnectUser() {
if (!this.chatService.chatClient?.user) {
return;
}
this.channelService.reset();
await this.chatService.disconnectUser();
}
User object
You can subscribe to the user$
Observable to get all important information (such us online state, unread count, etc) about the current user:
this.chatService.user$.subscribe((u) => console.log(u));
If there is no connected user, it will emit undefined
.