English
Models and HTTP services
Step 1. The DTOs as TypeScript types
Why. The API returns JSON shaped by the C# records of topics 8–11 and 12. If the client describes the same shapes as TypeScript types, the compiler checks every field the templates and stores read: a typo such as message.boddy is an error, not an undefined on screen. TypeScript types are erased at run time — they cost nothing and do not validate the server's answer; they are a contract the client trusts.
Hand-written types were chosen over generated ones (from the OpenAPI document of topic 12) because the client needs only a part of the API's surface, and a short, readable file is easier to learn from. The price is that a change of a DTO must be mirrored here by hand.
Do. Create the models:
ts
/** DTOs of the Chatex API. Ids are GUID strings, dates are ISO strings, enums are camelCase strings. */
export type ChatType = 'direct' | 'group' | 'channel';
export type ChatMemberRole = 'owner' | 'admin' | 'member' | 'subscriber';
export interface MyProfileDto {
id: string;
userName: string;
email: string;
displayName: string;
bio?: string | null;
hasAvatar: boolean;
createdAt: string;
}
export interface UserDto {
id: string;
userName: string;
displayName: string;
bio?: string | null;
hasAvatar: boolean;
lastSeenAt?: string | null;
}
export interface UserSummaryDto {
id: string;
userName: string;
displayName: string;
hasAvatar: boolean;
}
export interface AuthResponse {
accessToken: string;
accessTokenExpiresAt: string;
user: MyProfileDto;
}
export interface ChatDto {
id: string;
type: ChatType;
title?: string | null;
description?: string | null;
publicHandle?: string | null;
hasAvatar: boolean;
createdAt: string;
memberCount: number;
/** Null when the caller is not a member (public chat preview). */
myRole?: ChatMemberRole | null;
isMuted: boolean;
peer?: UserSummaryDto | null;
}
export interface LastMessageDto {
id: string;
senderId: string;
body: string;
createdAt: string;
}
export interface ChatListItemDto {
id: string;
type: ChatType;
title?: string | null;
hasAvatar: boolean;
lastActivityAt: string;
myRole: ChatMemberRole;
isMuted: boolean;
lastMessage?: LastMessageDto | null;
unreadCount: number;
peer?: UserSummaryDto | null;
}
export interface ChatSummaryDto {
id: string;
type: ChatType;
title?: string | null;
description?: string | null;
publicHandle?: string | null;
hasAvatar: boolean;
}
export interface ChatMemberDto {
user: UserSummaryDto;
role: ChatMemberRole;
joinedAt: string;
}
export interface AttachmentDto {
id: string;
fileName: string;
contentType: string;
sizeBytes: number;
}
export interface MessageDto {
id: string;
chatId: string;
sender: UserSummaryDto;
/** Null when the message is deleted. */
body?: string | null;
replyToMessageId?: string | null;
createdAt: string;
editedAt?: string | null;
isDeleted: boolean;
attachments: AttachmentDto[];
}
export interface PageDto<T> {
items: T[];
nextCursor?: string | null;
}
// Requests
export interface RegisterRequest {
userName: string;
email: string;
password: string;
displayName: string;
}
export interface LoginRequest {
login: string;
password: string;
}
export interface UpdateProfileRequest {
displayName: string;
bio?: string | null;
}
export interface ChangePasswordRequest {
currentPassword: string;
newPassword: string;
}
export interface CreateChatRequest {
type: 'group' | 'channel';
title: string;
description?: string | null;
publicHandle?: string | null;
memberIds?: string[];
}
export interface UpdateChatRequest {
title: string;
description?: string | null;
publicHandle?: string | null;
}
export interface SendMessageRequest {
body?: string | null;
replyToMessageId?: string | null;
attachmentIds?: string[];
}
/** Display name of a chat: direct chats have no title, so they use the peer's name. */
export function chatTitle(chat: { title?: string | null; peer?: UserSummaryDto | null }): string {
return chat.title || chat.peer?.displayName || 'Chat';
}
export function canManageChat(role: ChatMemberRole | null | undefined): boolean {
return role === 'owner' || role === 'admin';
}
/** Channels accept posts from owners and admins only. */
export function canPost(type: ChatType, role: ChatMemberRole | null | undefined): boolean {
if (!role) {
return false;
}
return type !== 'channel' || canManageChat(role);
}
/** UUIDv7 ids sort by creation time, so comparing the canonical strings orders messages. */
export function compareIds(a: string, b: string): number {
return a < b ? -1 : a > b ? 1 : 0;
}interfacedescribes the shape of an object, without a class behind it:JSON.parseproduces plain objects, and the interface tells the compiler what they contain. The names match the C# DTOs (ChatDto,MessageDto).- Ids are
string, dates arestring. JSON has no GUID or date type: the API sends GUIDs and ISO 8601 timestamps as strings, and the client keeps them so.new Date(iso)converts a date when it has to be displayed. - Enums are unions of string literals:
ChatTypeis'direct' | 'group' | 'channel', exactly the camelCase strings that the API'sJsonStringEnumConverterwrites (topic 12). field?: T | null—?means the property may be missing,| nullthat it may benull. The API omits nothing but sendsnullfor empty values; accepting both keeps the types honest for objects built in tests.MessageDto.bodyis null for a deleted message, as the comment says.PageDto<T>is the generic page of topic 7: the items and the opaquenextCursor.- Request types (
LoginRequest,SendMessageRequest, …) mirror the API's request records. - Small helpers that several features need live next to the types:
chatTitle(a direct chat has no title, so it shows the peer's name),canManageChatandcanPost— the client-side mirror ofChatPermissionsfrom topic 10, used only to hide buttons; the server still decides — andcompareIds. Because the API's ids are UUIDv7 (topic 4), comparing the strings orders messages by creation time.
Step 2. Observables and HttpClient
Why. Angular's HttpClient returns Observables from RxJS. An Observable is a lazy stream: nothing happens until someone subscribes, and then it can emit any number of values and complete or fail. For an HTTP call it emits one response (or, with observe: 'events', several progress events) and completes.
Observable, Promise, Task
A C# Task<T> is hot: the work has started when you get the task, and it completes once. A JavaScript Promise<T> is the same. An Observable<T> is cold and can emit many values: http.get(url) sends nothing until subscribe is called, and every subscription sends the request again. Chatex uses each where it fits: the HTTP services return Observables (that is what HttpClient gives), the stores turn single responses into Promises with firstValueFrom(observable) and use async/await like C#, and streams of many values — search input, hub events — stay Observables.
Step 3. One service per resource
Why. Every endpoint of the API gets one method in a thin service: the URL, the HTTP method and the types, nothing else. Components and stores never build URLs. The grouping follows the API's route groups (Table 16.1).
Table 16.1. The HTTP services of the client
| Service | Routes | Used from |
|---|---|---|
AuthApi | /api/auth/register, login, refresh, logout, logout-all | AuthService (this topic) |
ProfileApi | /api/me, /api/me/password, /api/me/avatar | the settings page (topic 21) |
UsersApi | /api/users, /api/users/{id} | user search (topic 18), profiles (topic 21) |
ChatsApi | /api/chats/…: list, create, direct, search, join, leave, members, roles, mute, read | the chat store and the chat pages (topics 18–21) |
MessagesApi | /api/chats/{id}/messages, /api/messages/{id} | the message store (topic 19) |
AttachmentsApi | /api/attachments | the composer (topic 19) |
Do. Create the services. The file is complete now; the later topics only call it.
ts
import { HttpClient, HttpEvent, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import {
AttachmentDto,
AuthResponse,
ChangePasswordRequest,
ChatDto,
ChatListItemDto,
ChatMemberDto,
ChatMemberRole,
ChatSummaryDto,
CreateChatRequest,
LoginRequest,
MessageDto,
MyProfileDto,
PageDto,
RegisterRequest,
SendMessageRequest,
UpdateChatRequest,
UpdateProfileRequest,
UserDto,
UserSummaryDto,
} from './models';
/** Builds query params, skipping null and undefined values. */
function params(values: Record<string, string | number | null | undefined>): HttpParams {
let result = new HttpParams();
for (const [key, value] of Object.entries(values)) {
if (value !== null && value !== undefined && value !== '') {
result = result.set(key, String(value));
}
}
return result;
}
function fileForm(file: File): FormData {
const form = new FormData();
form.append('file', file, file.name);
return form;
}
/** /api/auth: the refresh token travels in an HttpOnly cookie, see authInterceptor. */
@Injectable({ providedIn: 'root' })
export class AuthApi {
private readonly http = inject(HttpClient);
register(body: RegisterRequest): Observable<AuthResponse> {
return this.http.post<AuthResponse>('/api/auth/register', body);
}
login(body: LoginRequest): Observable<AuthResponse> {
return this.http.post<AuthResponse>('/api/auth/login', body);
}
refresh(): Observable<AuthResponse> {
return this.http.post<AuthResponse>('/api/auth/refresh', null);
}
logout(): Observable<void> {
return this.http.post<void>('/api/auth/logout', null);
}
logoutAll(): Observable<void> {
return this.http.post<void>('/api/auth/logout-all', null);
}
}
/** /api/me */
@Injectable({ providedIn: 'root' })
export class ProfileApi {
private readonly http = inject(HttpClient);
get(): Observable<MyProfileDto> {
return this.http.get<MyProfileDto>('/api/me');
}
update(body: UpdateProfileRequest): Observable<MyProfileDto> {
return this.http.put<MyProfileDto>('/api/me', body);
}
changePassword(body: ChangePasswordRequest): Observable<void> {
return this.http.put<void>('/api/me/password', body);
}
uploadAvatar(file: File): Observable<MyProfileDto> {
return this.http.put<MyProfileDto>('/api/me/avatar', fileForm(file));
}
deleteAvatar(): Observable<MyProfileDto> {
return this.http.delete<MyProfileDto>('/api/me/avatar');
}
}
/** /api/users */
@Injectable({ providedIn: 'root' })
export class UsersApi {
private readonly http = inject(HttpClient);
search(query: string, limit = 20): Observable<UserSummaryDto[]> {
return this.http.get<UserSummaryDto[]>('/api/users', { params: params({ query, limit }) });
}
get(id: string): Observable<UserDto> {
return this.http.get<UserDto>(`/api/users/${id}`);
}
}
/** /api/chats */
@Injectable({ providedIn: 'root' })
export class ChatsApi {
private readonly http = inject(HttpClient);
list(cursor?: string | null, limit = 30): Observable<PageDto<ChatListItemDto>> {
return this.http.get<PageDto<ChatListItemDto>>('/api/chats', {
params: params({ cursor, limit }),
});
}
create(body: CreateChatRequest): Observable<ChatDto> {
return this.http.post<ChatDto>('/api/chats', body);
}
direct(userId: string): Observable<ChatDto> {
return this.http.post<ChatDto>('/api/chats/direct', { userId });
}
search(query: string, limit = 20): Observable<ChatSummaryDto[]> {
return this.http.get<ChatSummaryDto[]>('/api/chats/search', {
params: params({ query, limit }),
});
}
get(id: string): Observable<ChatDto> {
return this.http.get<ChatDto>(`/api/chats/${id}`);
}
update(id: string, body: UpdateChatRequest): Observable<ChatDto> {
return this.http.put<ChatDto>(`/api/chats/${id}`, body);
}
delete(id: string): Observable<void> {
return this.http.delete<void>(`/api/chats/${id}`);
}
uploadAvatar(id: string, file: File): Observable<ChatDto> {
return this.http.put<ChatDto>(`/api/chats/${id}/avatar`, fileForm(file));
}
deleteAvatar(id: string): Observable<ChatDto> {
return this.http.delete<ChatDto>(`/api/chats/${id}/avatar`);
}
join(id: string): Observable<ChatDto> {
return this.http.post<ChatDto>(`/api/chats/${id}/join`, null);
}
leave(id: string): Observable<void> {
return this.http.post<void>(`/api/chats/${id}/leave`, null);
}
members(id: string, cursor?: string | null, limit = 50): Observable<PageDto<ChatMemberDto>> {
return this.http.get<PageDto<ChatMemberDto>>(`/api/chats/${id}/members`, {
params: params({ cursor, limit }),
});
}
addMembers(id: string, userIds: string[]): Observable<{ added: number }> {
return this.http.post<{ added: number }>(`/api/chats/${id}/members`, { userIds });
}
removeMember(id: string, userId: string): Observable<void> {
return this.http.delete<void>(`/api/chats/${id}/members/${userId}`);
}
setRole(id: string, userId: string, role: ChatMemberRole): Observable<void> {
return this.http.put<void>(`/api/chats/${id}/members/${userId}/role`, { role });
}
mute(id: string, muted: boolean): Observable<void> {
return this.http.put<void>(`/api/chats/${id}/mute`, { muted });
}
markRead(id: string, messageId: string): Observable<void> {
return this.http.post<void>(`/api/chats/${id}/read`, { messageId });
}
}
/** /api/chats/{id}/messages and /api/messages */
@Injectable({ providedIn: 'root' })
export class MessagesApi {
private readonly http = inject(HttpClient);
/**
* No cursor: the newest page, newest first. `before`: older pages, newest first.
* `after`: newer messages, oldest first (catching up after a reconnect).
*/
list(
chatId: string,
options: { before?: string | null; after?: string | null; limit?: number } = {},
): Observable<PageDto<MessageDto>> {
return this.http.get<PageDto<MessageDto>>(`/api/chats/${chatId}/messages`, {
params: params({ before: options.before, after: options.after, limit: options.limit ?? 50 }),
});
}
send(chatId: string, body: SendMessageRequest): Observable<MessageDto> {
return this.http.post<MessageDto>(`/api/chats/${chatId}/messages`, body);
}
edit(id: string, body: string): Observable<MessageDto> {
return this.http.put<MessageDto>(`/api/messages/${id}`, { body });
}
delete(id: string): Observable<void> {
return this.http.delete<void>(`/api/messages/${id}`);
}
}
/** /api/attachments: upload first, then send the ids with the message. */
@Injectable({ providedIn: 'root' })
export class AttachmentsApi {
private readonly http = inject(HttpClient);
upload(file: File): Observable<HttpEvent<AttachmentDto>> {
return this.http.post<AttachmentDto>('/api/attachments', fileForm(file), {
reportProgress: true,
observe: 'events',
});
}
}
export const avatarUrl = {
user: (id: string) => `/api/users/${id}/avatar`,
chat: (id: string) => `/api/chats/${id}/avatar`,
};
export const attachmentUrl = (id: string) => `/api/attachments/${id}`;private readonly http = inject(HttpClient)— the service getsHttpClientfrom the root injector. In Angular 22,HttpClientis provided in the root by default;app.config.tsstill callsprovideHttpClient(chapter 4) to add the interceptor.this.http.post<AuthResponse>(url, body)serialisesbodyto JSON, sends it and parses the response asAuthResponse. The type argument is a promise to the compiler, not a check.params(...)builds query strings and skipsnull,undefinedand empty values, solist(null)sends/api/chats?limit=30withoutcursor=.fileForm(file)wraps a file inmultipart/form-dataunder the field namefile, which the upload endpoints of topic 13 bind withIFormFile file.MessagesApi.listtakes the cursorsbeforeandafterof topic 11 in one options object, so a call readslist(chatId, { before: cursor }).AttachmentsApi.uploadasks forobserve: 'events'withreportProgress: the Observable then emits the request's events, not only the final response, and the composer (topic 19) shows the upload's state.avatarUrlandattachmentUrlbuild the URLs of files. The browser cannot load them with a plain<img src>, because they need the bearer token; topic 18 explains how they are loaded.
Check
powershell
npm run buildsucceeds. Nothing uses the new files yet, so the bundle does not grow: the build leaves out code that nothing imports.