Skip to content

About

A powerful, reusable, and standardized Angular service layer for making API requests. Standardizes all common data operations (CRUD, pagination, filtering) and offers centralized error and authorization handling.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

@chmolto/angular-core

npm Angular 20 License: ISC

A small, typed service layer for talking to REST APIs from Angular. Extend one class and you get CRUD, server-side pagination, filtering, file downloads and centralized error / 401 handling — without rewriting the same HttpClient boilerplate in every service.

It is the frontend counterpart of @chmolto/nestjs-core: both speak the same SearchRequest / FilterOperator format.

@Injectable({ providedIn: 'root' })
export class UsersService extends BaseCrudService<User, CreateUserDto, UpdateUserDto> {
  constructor(@Inject(API_URL) apiUrl: string) {
    super(apiUrl, '/users');
  }
}

// users.findAll(), users.findById(1), users.create(dto), users.updateById(1, dto),
// users.deleteById(1), users.deleteMany([1, 2]), users.findByPagination({ page: 2 })

Features

  • BaseCrudService<T, CreateDTO, UpdateDTO> — typed CRUD methods out of the box.
  • SearchRequestManager — keeps page, page size, sorting, search and filters state, and reloads the data with a loading flag.
  • Global error handling — every service reports errors to BaseApiService.error$ and 401s to BaseApiService.unauthorized$, so you show toasts and log out in one place.
  • File downloads — downloadFile() fetches a blob (e.g. an Excel export) and saves it.
  • Per-request options — skip the global error toast, send cookies or not, keep the stream open, pass query params.

Installation

npm install @chmolto/angular-core

Requires Angular 20 and RxJS 7.8.

Setup

Provide HttpClient and your API base URL.

Standalone app (app.config.ts):

import { provideHttpClient } from '@angular/common/http';
import { API_URL } from '@chmolto/angular-core';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(),
    { provide: API_URL, useValue: environment.apiUrl }, // e.g. 'https://api.example.com'
  ],
};

NgModule app:

import { AngularCoreModule } from '@chmolto/angular-core';

@NgModule({
  imports: [AngularCoreModule.forRoot(environment.apiUrl)],
  providers: [provideHttpClient()],
})
export class AppModule {}

The final URL is apiUrl + controllerPrefix + endpoint, so use a base URL without a trailing slash and prefixes that start with one ('/users').

Usage

CRUD service

import { Inject, Injectable } from '@angular/core';
import { API_URL, BaseCrudService } from '@chmolto/angular-core';

@Injectable({ providedIn: 'root' })
export class UsersService extends BaseCrudService<User, CreateUserDto, UpdateUserDto> {
  constructor(@Inject(API_URL) apiUrl: string) {
    super(apiUrl, '/users');
  }

  // Custom endpoints use the protected helpers: get, post, put, patch, delete
  activate(id: number) {
    return this.post<User>(`/${id}/activate`, {});
  }

  // Download a file generated by the backend
  exportToExcel(filters: Record<string, unknown>) {
    return this.downloadFile('/export', filters, 'users.xlsx');
  }
}
Method Request
findAll(params?) GET /users?…params
findById(id) GET /users/:id
create(dto) POST /users
updateById(id, dto) PATCH /users/:id
deleteById(id) DELETE /users/:id
deleteMany(ids) POST /users/delete-many with { ids }
findByPagination(searchRequest) POST /users/paginated → { data, page, limit, totalPages, total }

Paginated tables

import { FilterOperator, SearchRequestManager } from '@chmolto/angular-core';

@Component({ /* … */ })
export class UsersTableComponent {
  private users = inject(UsersService);

  readonly search = new SearchRequestManager((req) => this.users.findByPagination(req));
  readonly page$ = this.search.loadData();       // emits a new page on every reload()
  readonly loading$ = this.search.isLoading$;

  goToPage(page: number) {
    this.search.page = page;
    this.search.reload();
  }

  filterByRole(role: string) {
    this.search.filters = { role: { value: role, operator: FilterOperator.EQUALS } };
    this.search.page = 1;
    this.search.reload();
  }
}
@if (page$ | async; as page) {
  @for (user of page.data; track user.id) { <app-user-row [user]="user" /> }
  <app-paginator [page]="page.page" [totalPages]="page.totalPages" (pageChange)="goToPage($event)" />
}

Defaults: page = 1, limit = 15, sortBy = 'createdAt', sortOrder = 'desc'. Available operators: contains, equals, lessThan, greaterThan, startsWith, endsWith, in, between.

Global error and 401 handling

export class AppComponent {
  constructor() {
    BaseApiService.error$.pipe(takeUntilDestroyed()).subscribe((message) => toast.error(message));
    BaseApiService.unauthorized$.pipe(takeUntilDestroyed()).subscribe(() => auth.logout());
  }
}

Error messages are taken from the response body (error.message, joined if it is an array, as NestJS validation errors are), falling back to the HTTP status.

Request options

Every protected helper accepts a RequestOptions object:

Option Default Description
ignoreError false Don't emit on error$ (the observable still errors).
withCredentials true Send cookies with the request.
autoClose true Complete after the first response (take(1)).
params — HttpParams for the query string.
responseType 'json' 'json' or 'blob'.
this.get<Stats>('/stats', { ignoreError: true });

Development

npm install
npm run build-lib     # builds to dist/angular-core
npm run publish-lib   # publishes dist/angular-core to npm

License

ISC © Christian Moltó

About

A powerful, reusable, and standardized Angular service layer for making API requests. Standardizes all common data operations (CRUD, pagination, filtering) and offers centralized error and authorization handling.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages