Angular 9 NgRx Data tutorial - implementing a custom endpoint with query parameters for adding data

Currently, I am utilizing NgRx Data in my Angular 9 project and facing a challenge while trying to save a user using the add() method. The problem lies in the fact that the api endpoint has a structure 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 any approach to address this issue without altering the back-end endpoint?

Answer №1

Issue Resolved.

Implemented a new data service that extends DefaultDataService

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

import {EntityDataService} from '@ngrx/data';
import {NewDataService} from './new-data-service';
import {NgModule} from '@angular/core';

@NgModule({
    providers: [
        NewDataService
    ]
})
export class EntityStoreModule {
    constructor(
        entityDataService: EntityDataService,
        newDataService: NewDataService,
    ) {
        entityDataService.registerService('Item', newDataService);
    }
}

File path: src/app/store/new-data.service.ts

import {
    DefaultDataService,
    DefaultHttpUrlGenerator,
    DefaultPluralizer, HttpMethods,
    HttpUrlGenerator,
    Logger,
} from '@ngrx/data';
import {Injectable} from '@angular/core';
import {Item} from '../items/models/item.model';
import {HttpClient} from '@angular/common/http';
import {pluralNames} from './entity-metadata';
import {Observable} from 'rxjs';

@Injectable()
export class NewDataService extends DefaultDataService<Item> {
    constructor(
        http: HttpClient,
        httpUrlGenerator: HttpUrlGenerator,
        logger: Logger
    ) {
        logger.log(http, httpUrlGenerator);
        const url = new DefaultHttpUrlGenerator(new DefaultPluralizer([pluralNames]));
        url.registerHttpResourceUrls({Label: {entityResourceUrl: 'item', collectionResourceUrl: 'items'}});
        super('Item', http, url);
    }

    protected execute(method: HttpMethods, url: string, data?: any, options?: any): Observable<any> {
        if (method === 'POST') {
            url = 'client/' + 2 + '/item'; // where 2 will be replaced dynamically
        }

        return super.execute(method, url, data, options);
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a system for detecting changes in simple input elements and triggering a function to update the final result

There are a maximum of 12 inputs that represent the same entities or objects but with varying integer values. These values directly impact the final result displayed to the user. Whenever any of the input values change, a function needs to be triggered to ...

I'm having trouble understanding why I can't access the properties of a class within a function that has been passed to an Angular

Currently, I have integrated HTML 5 geolocation into an Angular component: ... export class AngularComponent { ... constructor(private db: DatabaseService) {} // this function is linked to an HTML button logCoords(message, ...

Angular: Guidelines for detecting checkbox change events and dynamically updating content in a separate component

One of my components contains a checkbox element: <mat-checkbox class="mr-5"></mat-checkbox>. I want to be able to detect when this checkbox is checked or unchecked, and based on its state, display text in a separate component that is ...

Retrieve the value of an ng-select component upon submitting a form

As a newcomer to Angular, I'm seeking guidance on how to properly handle form submissions with NgSelect in my project. Within my new-team.component.html file, I have the following code structure: <app-header></app-header> <div class="c ...

How can one retrieve the selected value from a dropdown menu in Angular?

Objective: My goal is to create a dropdown menu where users can select a value, which will then dynamically change the address of the website based on their selection. Issue: Although I managed to make the address change upon selection, it did so for ever ...

SonarLint versus SonarTS: A Comparison of Code Quality Tools

I'm feeling pretty lost when it comes to understanding the difference between SonarLint and SonarTS. I've been using SonarLint in Visual Studio, but now my client wants me to switch to the SonarTS plugin. SonarLint is for analyzing overall pr ...

Angular Signals - executing debounce within the effect() function

I have a scenario where I am dealing with a signal that is linked to an input field. My goal is to create an effect() for the searchTerm, but given that it depends on user input, I want to debounce that effect (using rxjs) to prevent the search from bein ...

Why is the selected option not visible in the Angular 8 drop-down?

This is a commonly asked question, but my situation seems to be unique. None of the existing answers have provided a solution for my specific issue. Here is the code that I am working with: <form (ngSubmit)="getExceptions(f)" #f="ngForm"> ...

What is the TypeScript counterpart of ParentClass.this?

Given the Java code snippet above, how would you achieve the same functionality in TypeScript as ParentClass.this.a? class ParentClass{ a: number = 1; class ChildrenClass{ b: number = 2; run(){ this.b = parentInstance.a; // Assuming &apo ...

Can a custom subscribe() method be implemented for Angular 2's http service?

Trying my hand at angular2, I discovered the necessity of using the subscribe() method to fetch the results from a get or post method: this.http.post(path, item).subscribe( (response: Response)=> {console.log(response)}, (error: any)=>{console.l ...

how to enhance Request type in Express by adding a custom attribute

In my quest to create a custom middleware function in Node.js using TypeScript, I am facing an issue where I am trying to save a decoded JSON web token into a custom request property called 'user' like so: function auth(req: Request, res: Respo ...

Tips for retrieving the body of a response in string format

My project involves an HTTP service that sends requests to the server and receives responses. Sometimes, different errors occur on the server during development which do not always return JSON. In such cases, I need to retrieve the response body as a strin ...

Adjust the starting color of a mat-input in Angular 9

I am encountering an issue with the styling of a standard matInput field within a mat-form-field, all contained within a [formGroup] div. The dark background of the parent element is causing visibility problems with the default dark text color of the input ...

When executing npm run build, the fonts are not displayed properly in Vite

I'm running 'npm run build' to compile my project, and then I use the 'npm run preview' command to view it. However, some images that I've set as background images in my SCSS file are not showing up. The same issue occurs with ...

Am I utilizing Angular's signals correctly? And what is the purpose of still requiring ChangeDetectorRef.detectChanges()?

I have been experimenting with signals and I am questioning whether the current use case would be more beneficial without using Signals and instead just having a "normal" class member swiper?: Swiper: @Component({ selector: '[app-test]', stan ...

Unable to instantiate a Vue reference with a potential null type

When working in Vue v3, I encountered a situation where I needed to create a ref with a type that could possibly be null. This specific scenario in my app involves data that starts off as null and then gets populated after loading completes. Just to illus ...

Oops! There was an unexpected error in the authGuard: [object Object] was not caught as expected

I've been working on implementing authGuard in my app, but I keep encountering an error. Below is the guard implementation: canActivate(route: ActivatedRouteSnapshot): Observable<boolean> { /** * Returning an observable of type boolea ...

Having trouble pushing data to a GraphQL database from my Next.js application

I am currently working on developing a Reddit-like platform. To simplify the process, I have integrated SQL with graphQL using Stepzen for endpoints. Below is the code snippet of my Post Box component for the site, which includes graphQL mutations.ts and q ...

Enhancing EventTarget in TypeScript (Angular 2+) for ES5 compilation

Is there a way to create a custom class that extends the EventTarget DOM API class? Let's say we have the following class: class MyClass extends EventTarget { constructor() { super(); } private triggerEvent() { this.dispatchE ...

Internet Explorer is throwing unexpected routing errors in Angular 2

I have a spring-boot/angular 2 application that is working perfectly fine on Chrome, Safari, Opera, and Edge. However, when accessed through Internet Explorer, the app directly routes to the PageNotFound component. I have tried adding shims for IE in the i ...