angulartypescriptngrxangular-ngrx-datangrx-data

Angulat 9 NgRx Data add method - create custom endpoint with query parameters;


I am using NgRx Data on an Angular 9 project and I am trying to save an user using the add() method. The downside is that the api endpoint is something like

http://localhost:{{port}}/something/{{clientId}}/users

UserComponent

saveUser(user) {
    this.userService.add(user);
}

UserService

export class UserService extends EntityCollectionServiceBase<User> {
        constructor(serviceElementsFactory: EntityCollectionServiceElementsFactory) {
            super('User', serviceElementsFactory);
        }
    }

Is there a method to solve this issue? I don`t want to modify the back-end endpoint.


Solution

  • Solved.

    Registered a new data service that extends DefaultDataService

    src/app/store/entity-store-module.ts

    import {EntityDataService} from '@ngrx/data';
    import {TestDataService} from './test-data-service';
    import {NgModule} from '@angular/core';
    
    @NgModule({
        providers: [
            TestDataService
        ]
    })
    export class EntityStoreModule {
        constructor(
            entityDataService: EntityDataService,
            testDataService: TestDataService,
        ) {
            entityDataService.registerService('User', testDataService);
        }
    }
    

    src/app/store/test-data.service.ts

    import {
        DefaultDataService,
        DefaultHttpUrlGenerator,
        DefaultPluralizer, HttpMethods,
        HttpUrlGenerator,
        Logger,
    } from '@ngrx/data';
    import {Injectable} from '@angular/core';
    import {User} from '../users/models/user.model';
    import {HttpClient} from '@angular/common/http';
    import {pluralNames} from './entity-metadata';
    import {Observable} from 'rxjs';
    
    @Injectable()
    export class TestDataService extends DefaultDataService<User> {
        constructor(
            http: HttpClient,
            httpUrlGenerator: HttpUrlGenerator,
            logger: Logger
        ) {
            logger.log(http, httpUrlGenerator);
            const url = new DefaultHttpUrlGenerator(new DefaultPluralizer([pluralNames]));
            url.registerHttpResourceUrls({Label: {entityResourceUrl: 'user', collectionResourceUrl: 'users'}});
            super('User', http, url);
        }
    
        protected execute(method: HttpMethods, url: string, data?: any, options?: any): Observable<any> {
            if (method === 'POST') {
                url = 'client/' + 1 + '/user'; // where 1 will be replaced dynamically
            }
    
            return super.execute(method, url, data, options);
        }
    }