Consolidate all REST service requests and match the server's response to my specific object model

My goal was to develop a versatile REST service that could be utilized across all my services. For instance, for handling POST requests, the following code snippet demonstrates how I implemented it:

post<T>(relativeUrl: string, body?: any,  params?: HttpParams, headers?: HttpHeaders): Observable<HttpResponse<T>> {
        return this.executeRequest(this.createRequest(relativeUrl, body, params, headers, 'POST'))
    }

A similar approach was taken for other HTTP request methods as well. These methods make use of the createRequest and executeRequest functions.

// TODO: Finish and check arguments
    private createRequest(relativeUrl: string, body: any, params: HttpParams | null, headers: HttpHeaders | null, method: string ): HttpRequest<any> {

        let url: string;
        if (relativeUrl.startsWith('http') || relativeUrl.startsWith('https')) {
            url = relativeUrl;
        } else {
            url = `${environment.restUrl}/${relativeUrl}`;
        }


        headers = headers || new HttpHeaders()
        //TODO: If user is logged add Authorization bearer in headers

        return new HttpRequest(method, url, body, {
            headers: headers,
            params: params
        })
    }

    private executeRequest(request: HttpRequest<any>): Observable<HttpResponse<any>> {
        return <any> this.http.request(request)
            .pipe(
                catchError(error => {
                    return throwError(error);
                })
            );
    }

I have some queries regarding the implementation of these methods. Are they properly structured? Is the response from the HTTP requests handled correctly? As an example, my login.service utilizes the POST method in the following manner:

login<User>(email: string, password: string): Observable<HttpResponse<User>>{

        const data = {
            email: email,
            password: password
        };

        let headers = new HttpHeaders({
            'Content-Type':  'application/json',
            'Accept-Language': 'it'
        })

        return this.restService.post<User>(this.baseUrl, data, null, headers)
            .pipe(
                catchError(error => {
                    this.notificationService.error(error.error.error.message);
                    return throwError(error);
                })
            );
    }

One concern relates to the conversion of JSON data returned from the server into my User object. Should this conversion take place within the service or should it be handled by the component utilizing the loginService? Additionally, is it appropriate to perform the conversion using Object.assign(new User(), serverResponse.body)?

Answer №1

One effective way to apply the same logic to all your requests is by utilizing Http Interceptors in Angular.

A helpful example of this can be found in Damien Bod's angular-auth-oidc-client library.

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    private oidcSecurityService: OidcSecurityService;

    constructor(private injector: Injector) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let requestToForward = req;

        if (this.oidcSecurityService === undefined) {
            this.oidcSecurityService = this.injector.get(OidcSecurityService);
        }
        if (this.oidcSecurityService !== undefined) {
            let token = this.oidcSecurityService.getToken();
            if (token !== '') {
                let tokenValue = 'Bearer ' + token;
                requestToForward = req.clone({ setHeaders: { Authorization: tokenValue } });
            }
        } else {
            console.debug('OidcSecurityService undefined: NO auth header!');
        }

        return next.handle(requestToForward);
    }
}

Reference:https://github.com/damienbod/angular-auth-oidc-client

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

Troubleshooting why the Angular innerHTML function is failing to render the specified

I'm encountering this problem where I am receiving a string const str = '<p>Please ensure Process Model diagram represents Functions adequately (boxes that represent an activity or group of activities that produce an outcome):</p>< ...

I seem to be missing some properties in the request body schema. Why am I receiving an incomplete model for

Seeking assistance in grasping the working of models in loopback4. Here's a model I defined: @model() export class ProductViewConfig extends BaseConfig { @property({ type: 'string', id: true, generated: true, }) _id?: strin ...

Error message: "Unable to find a windows instance" encountered while conducting tests on Paho MQTT Client using mocha and typescript

After spending countless days searching online, I have yet to find any resources on testing the Paho MQTT Client. My approach so far has been somewhat naive, as shown below: import { suite, test, slow, timeout, skip, only } from 'mocha-typescript&apo ...

Retrieving the returned value from an Observable of any type in Angular Typescript (Firebase)

I am working on retrieving data from my Firebase User List using the following code: currentUserRef: AngularFireList<any> currentUser: Observable<any>; var user = firebase.auth().currentUser; this.currentUserRef = this.af.list('usuarios ...

Is there a way to extract information from an HttpClient Rest Api through interpolation?

I am currently facing an issue with a component in my project. The component is responsible for fetching data from a REST API using the HttpClient, and the data retrieval seems to be working fine as I can see the data being logged in the Console. However, ...

Issue with ngStyle not functioning properly with conditional operator

I am currently learning how to use Angular4 ngStyle by going through a tutorial. Here's the code I have been working on: app.component.html <button [ngStyle]="{ 'backgroundColor': canSave ? 'blue': 'gray', ...

Creating a dynamic dropdown menu where the available options in one select box change based on the selection made in another

Looking at the Material-UI Stepper code, I have a requirement to create a select element with dynamic options based on the selected value in another select within the same React component. To achieve this, I wrote a switch function: function getGradeConte ...

My customized mat-error seems to be malfunctioning. Does anyone have any insight as to why?

Encountering an issue where the mat-error is not functioning as intended. A custom component was created to manage errors, but it is not behaving correctly upon rendering. Here is the relevant page code: <mat-form-field appearance="outline"> < ...

The takeUntil function will cancel an effect request if a relevant action has been dispatched before

When a user chooses an order in my scenario: selectOrder(orderId): void { this.store$.dispatch( selectOrder({orderId}) ); } The order UI component triggers an action to load all associated data: private fetchOrderOnSelectOrder(): void { this.sto ...

React: Switching PopUp causes the entire component to be re-rendered

Currently, I am in the process of familiarizing myself with React, so I appreciate your patience. I am developing a component using MaterialUI which consists of a grid and a PopOver. A basic mockup of this component is as follows: export const Overview ...

the hidden input's value is null

I am encountering an issue with a hidden input in this form. When I submit the form to my API, the value of the input is empty. Isbn and packId are both properties of a book model. However, for some reason, the value of packId is coming out as empty. & ...

Issue with toggling in react js on mobile devices

Currently, I am working on making my design responsive. My approach involves displaying a basket when the div style is set to "block", and hiding it when the user browses on a mobile device by setting the display to "none". The user can then click on a but ...

What is the best way to conceal a specific list item in an Angular 2 template?

I need help figuring out how to hide a selected list item that has been added to another list. I want the added item to be hidden from view in the original list. <div class="countries-list"> <span class="countries-list__header">{{'G ...

Is there a way to enable intellisense in vscode while editing custom CSS within a material-ui component?

Is there a vscode extension recommendation for intellisense to suggest css-in-js for customized material ui components in .tsx files? For example, I want intellisense to suggest 'backgroundColor' when typing. The closest I found is the 'CSS- ...

What are the steps to setting up SystemJS with Auth0?

I am having trouble configuring SystemJS for Auth0 (angular2-jwt) and Angular 2.0.0-beta.6 as I keep encountering the following error message: GET http://localhost:3000/angular2/http 404 (Not Found)fetchTextFromURL @ system.src.js:1068(anonymous function) ...

Having trouble with the disabled property in Angular 10? Learn how to properly use it and troubleshoot

---Update--- I had previously posted this question without receiving a solution. I came across a Github blog that mentioned the "isButtonDisabled" alone may not work and a function needs to be called instead. In my TypeScript code, I can only generate a b ...

Verify whether the type of the emitted variable aligns with the specified custom type

Currently, I am in the process of testing Vue 3 components using jest. My main objective is to receive an emit when a button is clicked and then verify if the emitted object corresponds to a custom type that I have defined in a separate file. Below is an e ...

Issues with property binding in Angular are causing problems

Suppose the app component has a variable defined for the value in the input field. However, every time the button event is triggered, the string is printed as empty and the binding does not seem to work at all. export class AppComponent { numVal =1235; ...

Challenges arise with dependencies during the installation of MUI

[insert image description here][1] I attempted to add mui styles and other components to my local machine, but encountered a dependency error. How can I resolve this issue? [1]: https://i.stack.imgur.com/gqxtS.png npm install @mui/styles npm ERR! code ERE ...

Issue: Debug Failure. Invalid expression: import= for internal module references should have been addressed in a previous transformer

While working on my Nest build script, I encountered the following error message: Error Debug Failure. False expression: import= for internal module references should be handled in an earlier transformer. I am having trouble comprehending what this erro ...