Skip to content

Configuration

Michael Dostál edited this page Nov 14, 2018 · 1 revision

Firstly, create your Datastore service:

  • Extend the JsonApiDatastore class
  • Decorate it with @JsonApiDatastoreConfig, set the baseUrl for your APIs and map your models (Optional: you can set apiVersion, baseUrl will be suffixed with it)
  • Pass the HttpClient depencency to the parent constructor.
import { JsonApiDatastoreConfig, JsonApiDatastore, DatastoreConfig } from 'angular2-jsonapi';

const config: DatastoreConfig = {
  baseUrl: 'http://localhost:8000/v1/',
  models: {
    posts: Post,
    comments: Comment,
    users: User
  }
}

@Injectable()
@JsonApiDatastoreConfig(config)
export class Datastore extends JsonApiDatastore {

    constructor(http: HttpClient) {
        super(http);
    }

}

Then set up your models:

  • Extend the JsonApiModel class
  • Decorate it with @JsonApiModelConfig, passing the type
  • Decorate the class properties with @Attribute
  • Decorate the relationships attributes with @HasMany and @BelongsTo
  • (optional) Define your Metadata
import { JsonApiModelConfig, JsonApiModel, Attribute, HasMany, BelongsTo } from 'angular2-jsonapi';

@JsonApiModelConfig({
    type: 'posts'
})
export class Post extends JsonApiModel {

    @Attribute()
    title: string;

    @Attribute()
    content: string;

    @Attribute({ serializedName: 'created-at' })
    createdAt: Date;

    @HasMany()
    comments: Comment[];
}

@JsonApiModelConfig({
    type: 'comments'
})
export class Comment extends JsonApiModel {

    @Attribute()
    title: string;

    @Attribute()
    created_at: Date;

    @BelongsTo()
    post: Post;

    @BelongsTo()
    user: User;
}

@JsonApiModelConfig({
    type: 'users'
})
export class User extends JsonApiModel {

    @Attribute()
    name: string;
    // ...
}
Clone this wiki locally