"Launching" conduit for Observable

Is there a way to attach two pipes to an HttpClient request in order to execute functions at the beginning and end of the request? I have discovered the "finalize" operator for executing a function when the request is finished, but I am looking for an equivalent for the start of the request. Here's what my code looks like:

this.http.get<MyModel>('api/model')
    .pipe(
      // TODO missing something for startup
      finalize(() => console.log('on start'))
    )
    .subscribe(result => {
      console.log(result);
    });

How can I achieve this desired outcome? Are there any built-in operators in RxJS that could help with this, or will I need to create my own solution? Any alternative suggestions?

Answer №1

UPDATE: I have discovered a more obscure solution that works well. There exists a defer Observable creation function, which is not commonly recognized as an operator.

This method can be implemented in the following manner:

defer(() => {
    console.log('initializing');
    return this.http.get<MyModel>('api/model').pipe(
        finalize(() => console.log('finalizing'))
    )
}).subscribe(response => {
    console.log(response);
});

An advantage of this approach is that it encapsulates the HttpClient within a closure, allowing you to share and use the Observable without immediately subscribing to it.


startWith is a similar operator available for use, although it requires matching the type of the HTTP response.

Answer №2

Following @Tomasz Błachut's suggestion using the startWith operator, I managed to implement a solution that meets my requirements. It involves some clever tricks but functions as intended.

The approach is to utilize the startWith operator along with an immediately invoked function that carries out the necessary actions and returns null. By then applying skip(1), we are able to bypass this null value in our subscription.

The end result works flawlessly. Here is the updated code:

this.http.get<MyModel>('api/model')
    .pipe(
      startWith((() => {
        console.log('on start');
        return null;
      })()),
      skip(1),
      finalize(() => console.log('on end'))
    )
    .subscribe(result => {
      console.log(result);
    });

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

Set the datepicker with the window positioned to the right side

In my current project, I am utilizing Angular 13, Bootstrap 5, and ngx-bootstrap-fix-datepicker version 5. "bootstrap": "^5.1.3", "ngx-bootstrap": "^8.0.0", "ngx-bootstrap-fix-datepicker": "^5.6.8" ...

A conditional type used with an array to return either an Error object or a generic type when the array is destructured

Within my Typescript project, I've implemented a Result type to be returned from functions, containing either an error or some data. This can take the form of [Error, null], or [null, Data]. Here's an example: type Result<Data> = [ Error | ...

Having Trouble with Angular2: Nesting a Child Component?

Working with angular 2 has been a fun experience for me over the past few days. I've been attempting to insert a child selector into a parent template, but it seems more challenging than I expected. Every time I try, I encounter the following error: ...

Compelling users to upgrade to the latest version of the Angular 5 application

My Angular 5 application is currently deployed on Azure using ng build --prod. I am looking for a way to ensure that users are always prompted to download the latest version of the application, including any updates to style sheets. However, I have notic ...

Clear drop down selections after button is pressed

I am currently working with a grid in my template that contains multiple dropdowns, each row having its own. When I click a button, I gather the values from these dropdowns. However, upon clicking this button, I wish to reset all the dropdowns back to thei ...

Error Arises When Making Selection in PrimeNG's P-ListBox Component

Whenever I choose an item from my listbox module, I encounter an error where the value is being returned as an object instead of an array in my listbox.js file from p-listbox by PrimeNG. HTML: <p-listbox formControlName="programType" [options]="phoneT ...

Disabling ion-select in Ionic 2 with Typescript

To disable an ion-select element in Angular, you can use the disabled attribute like this: <ion-item> <ion-label stacked>Property Type</ion-label> <ion-select [(ngModel)]="propType" (ionChange)="ionChanger()" di ...

Having trouble iterating over an array in Angular's TypeScript

I've been attempting to loop through an array of objects in TypeScript, but encountered the following error: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'forEach' of undefined TypeError: Cannot read property 'fo ...

Enhancing native JavaScript types in TypeScript 1.8 with the power of global augmentation

Currently, I am working on expanding the capabilities of native JavaScript types using the new global augmentation feature in TypeScript 1.8, as detailed in this resource. However, I'm encountering difficulties when the extension functions return the ...

A guide to confirm if an object includes an HTML element without compromising safety

When I implement a function that is triggered by a click event: useEffect(() => { document.addEventListener('click', (e) => handleClickOutside(e), true); }); The function itself: const myElement = useRef(null); const handleCli ...

Toggle the enableCheckboxSelector based on a specific condition

In my implementation of angular slickgrid, the enableCheckboxSelector is set to true by default in the grid options. However, I need to selectively hide checkboxes for all rows based on a dropdown value change. I tried the following code snippet: if(isRead ...

Obtain a 404 error status code when the route cannot be found in Angular 6+ using Universal

After launching my project with Universal, I set up my .htaccess file to direct all requests to the index.html, which serves as the root page for my Angular application. I followed the instructions on https://angular.io/guide/universal to enable sharing l ...

What are the steps for launching an Angular application?

Running on ubuntu 18.0.4, I had angular-cli installed. Attempting to create a new app named conFusion using the command: ng new conFusion -dir=./conFusion --style=scss. CREATE conFusion/README.md (1026 bytes) CREATE conFusion/angular.json (3666 by ...

Animating with Angular 2

As I delve into this informative resource, my goal is to incorporate some animations into my applications, but I find myself grappling with understanding how the animations are triggered. HTML Component <div class="navbar navbar-default navbar-fixed-t ...

Although Angular allows for CSS to be added in DevTools, it seems to be ineffective when included directly in

Looking to set a maximum length for ellipsis on multiline text using CSS, I tried the following: .body { overflow: hidden; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; } However, this approach did not work. Interesti ...

Issue with absolute import in React TypeScript application

An error occurs when trying to import a module, displaying the following message: Compiled with problems: × ERROR in ./src/App.tsx 5:0-33 Module not found: Error: Can't resolve 'routes' in 'F:\Tamrinat\Porfolio\microsite ...

Universal function for selecting object properties

I've recently delved into TypeScript coding and have run into a puzzling issue that has me stumped. Take a look at the code snippet below: interface testInterface { a: string; b: number; c?: number; } const testObject: testInterface = { a: & ...

Angular application featuring scrolling buttons

[Apologies for any language errors] I need to create a scrollable view with scroll buttons, similar to the image below: Specifications: If the list overflows, display right/left buttons. Hide the scroll buttons if there is no overflow. Disable the le ...

Ways to verify the existence and non-empty status of a directory?

zip.loadAsync(files).then(function(directory:any){ if (directory.folder("Mary")){ console.log("fail"); } else{ directory.folder("Mary").forEach(function (filename: any) {Console.log(filename);}); }; } I am attem ...

Nest is unable to resolve the dependencies of the ItemsService. Ensure that the required argument at index [0] is present within the AppModule context

After following the Nest JS Crash tutorial from a Youtube Link, I encountered an error when importing an interface in the service. Nest seems unable to resolve dependencies of the ItemsService. It's important to ensure that the argument at index [0 ...