@datx/jsonapi-angular
DatX is an opinionated data store for use with the MobX state management library. It features support for simple observable property definition, references to other models and first-class TypeScript support.
@datx/jsonapi-angular
is a datx mixin that adds JSON API support for Angular applications.
Configuration
First, create a collection and provide it under APP_COLLECTION
token:
import { InjectionToken } from '@angular/core';
import { Collection } from '@datx/core';
import { jsonapiAngular } from '@datx/jsonapi-angular';
export const APP_COLLECTION = new InjectionToken<AppCollection>('App collection');
export class AppCollection extends jsonapiAngular(Collection) {
public static readonly types = [...];
}
import { AppCollection, APP_COLLECTION } from './collections/app.collection';
@NgModule({
providers: [
{
provide: APP_COLLECTION,
useValue: new AppCollection(),
},
],
})
export class AppModule {}
Next, provide DATX_CONFIG
with your own values for the config:
import { DATX_CONFIG, setupDatx } from '@datx/jsonapi-angular';
import { AppCollection, APP_COLLECTION } from '.collections/app.collection';
@NgModule({
provides: [
{
provide: APP_COLLECTION,
useValue: new AppCollection(),
},
{
provide: DATX_CONFIG,
useFactory: (httpClient: HttpClient) => {
return setupDatx(httpClient, {
baseUrl: '/api/v1/',
});
},
deps: [HttpClient],
},
],
})
export class AppModule {}
Basic usage example
Create the base model:
import { IType, Model } from '@datx/core';
import { jsonapiAngular } from '@datx/jsonapi-angular';
export class BaseModel extends jsonapiAngular(Model) {
public get id(): IType {
return this.meta.id;
}
}
Create specific domain models and add them to types
in AppCollection
import { Attribute } from '@datx/core';
import { BaseModel } from 'src/app/base-model';
export class Artist extends BaseModel {
public static endpoint = 'artists';
public static type = 'project';
@Attribute()
public name!: string;
}
export class AppCollection extends jsonapiAngular(Collection) {
public static readonly types = [Artist];
}
Create services for managing the models (one service per model):
import { Inject, Injectable } from '@angular/core';
import { CollectionService } from '@datx/jsonapi-angular';
@Injectable({
providedIn: 'root',
})
export class ArtistsService extends CollectionService<Artist, AppCollection> {
protected ctor = Artist;
}
Inject the service in your component or other services and use methods like getManyModels
and getOneModel
:
export class ArtistsComponent {
public artists$ = this.artistsService.getAllModels();
constructor(private readonly artistsService: ArtistsService) {}
}
That's it!