1

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.

  • Why can’t you pass port to the userService.add method? May be I am not clear about question. – Hamza Zaidi Jun 26 '20 at 13:11
  • It is not about the port, it is about that clientId. I need to dynamically set that parameter. When you make a POST request you cannot set that parameter due to the NgrxData limitations. In your controller you just call the service add() method and NgrxData makes a POST request to '/api/user/' in my example. That is the way NgrxData works. – Alexandru Dumitru Jun 30 '20 at 10:31

1 Answers1

1

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);
    }
}