What is the best way to include custom RequestOptionsArgs in an Angular 2 request?

My customized Http service includes a method that handles requests with a loading indicator that displays when the request begins and hides when it ends.

request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
    this.loadingService.start();

    if (!options) {
        options = {};
        options.headers = new Headers();
    }
    this.updateHeaders(options.headers);
    if (typeof url !== 'string') {
        this.updateHeaders(url.headers);
    }

    return super.request(url, options)
        .catch((response: Response) => this.authError(response))
        .finally(() => {
            this.loadingService.done();
        });
}

Although the loading indicator shows and hides accordingly, I want to have control over which requests trigger the loader. How can I accomplish this?

The RequestOptionsArgs interface defines various properties, but using them to determine when to show the loading indicator may not be ideal.

export interface RequestOptionsArgs {
    url?: string;
    method?: string | RequestMethod;
    search?: string | URLSearchParams;
    headers?: Headers;
    body?: any;
    withCredentials?: boolean;
    responseType?: ResponseContentType;
}

What alternatives do I have in order to selectively show or hide the loading indicator?

Answer №1

Create a custom HTTP request using the http service within your service without overriding the original service.

Next, define two methods: one for handling requests with a loading service (loadingService) and another for requests without it.

requestWithLoading(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
    this.loadingService.start();

    if (!options) {
        options = {};
        options.headers = new Headers();
    }
    this.updateHeaders(options.headers);
    if (typeof url !== 'string') {
        this.updateHeaders(url.headers);
    }

    return http.request(url, options)
        .catch((response: Response) => this.authError(response))
        .finally(() => {
            this.loadingService.done();
        });
}

requestNonLoading(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {

    if (!options) {
        options = {};
        options.headers = new Headers();
    }
    this.updateHeaders(options.headers);
    if (typeof url !== 'string') {
        this.updateHeaders(url.headers);
    }

    return http.request(url, options)
        .catch((response: Response) => this.authError(response))
        .finally(() => {});
}

Answer №2

1.Solution : Ensure that this.loadingService.start(); is moved into your component.

2.Solution : Alternatively, define a parameter isLoading :boolean = true in the service.

request(url: string|Request, options?: RequestOptionsArgs, isLoading:boolean = true): Observable<Response> {
  if(isLoading){
     this.loadingService.start();
   }


    if (!options) {
        options = {};
        options.headers = new Headers();
    }
    this.updateHeaders(options.headers);
    if (typeof url !== 'string') {
        this.updateHeaders(url.headers);
    }

    return super.request(url, options)
        .catch((response: Response) => this.authError(response))
        .finally(() => {
            this.loadingService.done();
        });
}

Set the default value to true or false based on what is more appropriate for your needs.

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

The comparison between StrictNullChecks and Union Types in terms of syntax usage

Understanding StrictNullChecks in TypeScript Traditionally, null and undefined have been valid first class type citizens in JavaScript. TypeScript formerly did not enforce this, meaning you couldn't specify a variable to potentially be null or unde ...

What could be causing the Angular HTTPClient to make duplicate REST calls in this scenario?

I am encountering an issue with my Angular service that consumes a Rest API. Upon inspecting the network and the backend, I noticed that the API is being called twice every time: Here is a snippet of my Service code: getAllUsers():Observable<any>{ ...

Linking children to their parents in a mat tree structure

I'm looking to create a mat tree based on the provided diagram. https://i.sstatic.net/cTY2w.png So far, I've managed to design the icons and boxes, but I'm struggling with drawing the connecting lines. Can anyone assist me with this part? I ...

How to transfer the returned value from an anonymous callback function to the `this` keyword in an ionic2 angular4 project

Currently, I am utilizing a custom geolocation provider that operates asynchronously. It takes approximately 3-5 seconds to retrieve the user's location. Using an anonymous callback function works fine when I console.log the results and view the value ...

After a loop, a TypeScript promise will be returned

I am facing a challenge in returning after all calls to an external service are completed. My current code processes through the for loop too quickly and returns prematurely. Using 'promise.all' is not an option here since I require values obtain ...

Decrease the construction duration within a sprawling Angular 8 project

It takes nearly 10-15 minutes to compile the project in production mode, resulting in a dist folder size of 32MB Here are the production options I am currently using:- "production": { "optimization": true, "outputHashing": "all", ...

What is the best way to apply a filter to an array of objects nested within another object in JavaScript?

I encountered an issue with one of the API responses, The response I received is as follows: [ {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}, {type: "County", countyNa ...

How to send parameters with the fetch API

After completing a task that involved converting code from Angular HttpClient to using fetch API, I encountered an issue with passing parameters. Below is the original code snippet before my modifications: let activeUrl = new URL(this.serverAddress); ...

How can we limit the CSS properties that can be used in an interpolated manner by defining a restricted TS type for CSS props based on emotions?

When dealing with emotions, how can we specify a restricted TS type for the css prop to only allow certain css properties to be interpolated? For instance, consider the following scenario: // This is considered valid css = {{ color: 'white', ...

When retrieving objects using Angular's HttpClient, properties may be null or empty

I am working with a service class in Angular that utilizes the HttpClient to retrieve data from a web service. The web service responds with a JSON object structured like this: { "id": "some type of user id", "name": "The name of the user", "permiss ...

Unable to connect my Angular library with another Angular library

Issue with Angular Libraries Within my project, I have created several angular libraries stored in different folders: /home/user/lib1 /home/user/lib2 /home/user/lib3 The lib2 and lib3 libraries are dependent on the lib1 library. // Example of the lib3.m ...

A step-by-step guide on creating a Decorator using the TypeScript compile API

How can I create a custom class in TypeScript with multiple 'class-validator' decorators to ensure the property types are correct? I am considering using `ts.factory.createDecorator`, but I'm unsure how to obtain a `ts.Expression` for it. ...

I am unable to showcase the image at this time

Hey there, I'm having an issue with displaying an image stored inside the NextJS API folder. The alt attribute is showing up fine, but the actual image isn't displaying. When I console.log the image data, everything seems to be in place. Can anyo ...

Generating a form structure from json containing repeated inputs: Control with path formArray could not be located

Currently, I am in the process of constructing a form using JSON data. My backend is implemented with Spring Boot, which returns the following object to an Angular frontend: { "controls": [ { "name": "genre", ...

Associate text with a color from a predetermined list (JavaScript)

As I work on adding tags to my website for blog posts, I have a specific vision in mind. Each tag should be assigned a unique background color selected from a predefined array of theme colors. My goal is to assign the same background color to tags with id ...

What is the method for obtaining the union type of interface values (including string enums)?

How can I achieve the following ? Given : enum FooEnum1 { Foo = "foo", }; enum FooEnum2 { Foo = 1, }; interface FooInterface { foo1 : FooEnum1, foo2 : FooEnum2, foo3 : string, foo4 : number, }; I am interested in cre ...

What is the best way to rid ourselves of unwanted values?

In the laravel-vue-boilerplate package, there is a User CRUD feature. I duplicated this functionality to create an Item CRUD by making some changes and adjustments. Everything is working fine except for one issue: after editing an item, when trying to add ...

Error message "Property 'name' does not exist on type '{}'" is encountered when using Ionic/Angular HttpClient and no data type is specified

While working on my Ionic project, I encountered an error in Angular when trying to fetch data from an API using HttpClient. The error message that popped up was 'Property 'name' does not exist on type '{}'.'. Below is the cod ...

Why is it that the resource fails to load in an Angular localhost environment when making an http request?

In the realm of ASP.NET MVC projects lies my creation, a masterpiece utilizing Angular UI components powered by ASP.NET WebAPI. As an explorer navigating the unknown territory of Angular, I present to you the sacred texts residing within my project. Behol ...

"Troubleshooting the placement problem in Angular Material's md-menu

I am currently utilizing the md-component for Angular 2 from Angular Material. I am carefully following the documentation's instructions on how to integrate it into my project, but I am encountering an issue where the menu opens up below the trigger. ...