How can I invoke a function in a Component using an HttpInterceptor?

Can a function in a Component be triggered from an HttpInterceptor?

@Injectable()
export class HttpResponseInterceptor implements HttpInterceptor {

  // constructor(@Inject(DOCUMENT) private document: any) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('HttpRequest<any> called');
    const started = Date.now();
    // Trigger component function
    return next.handle(req).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // Execute component function on response
      }
    });
  }

}

Answer №1

Avoid calling a component method from a service as it is not considered best practice. Instead of passing the class instance of that component into the service, which requires publicly accessible properties, opt for a cleaner approach.

One recommended alternative is to add to an observable stream from a service and allow components to subscribe to this stream, enabling them to call desired functions. This follows "the Angular way" of handling such situations.

By using this method, you can retrieve the same data across multiple components and execute various functions within those components. Simply utilize the subscribe() function.

For example:

@Injectable()
export class HttpResponseInterceptor {
    dataStream: ReplaySubject<any> = new ReplaySubject();

    dataStream$(): Observable<any> {
        return this.dataStream().asObservable();
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('HttpRequest<any> called');
        const started = Date.now();

        return next.handle(req).do((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse) {
                // Include data in the `next()` function. 
                // Any subscription function in your components will be triggered upon each call.
                this.dataStream.next(...);
            }
        });
    }
}

@Component({...})
export class MyComponent {
    ngOnInit() {
        this.httpInterceptorService.dataStream$().subscribe(data => {
            // Triggered whenever new data is added to the stream in your HttpInterceptorService class.
            // Implement any necessary custom functionality here...
        });
    }
}

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 issue with adding rows to a dynamic HTML Table in Angular is that it is causing the previous rows to disappear

I have created a neat HTML table with three columns: <table > <thead> <tr> <td class="tdBorderEmail"><label>Action</label></td> <td class="tdBorderEmai ...

What is the best method for accessing all the projected elements within a Component?

What is the best approach for accessing all projected elements within a Component? Consider an example where AppComponent projects various links and images into TestComponent: @Component({ selector: 'test', template: '<ng-content> ...

The interface "App" is not properly implemented by the class "FirebaseApp" causing an error

My attempt to set up AngularCLI and Firebase led to encountering this issue... How should I proceed? ERROR in node_modules/angularfire2/app/firebase.app.module.d.ts(5,22): error TS2420: Class 'FirebaseApp' does not properly implement interface ...

Greetings, I am currently using Angular version 3n 2 rc5 and I am hoping to execute a function called "change" that will perform two separate functions

I am working on a piece of code where I need to assign a value to a variable and then trigger a function simultaneously. I have attempted the following approach, but I am not sure if it is correct. Can someone provide some assistance? view.html <input ...

Tips for parsing data arrays in HTML templates

I have three variables and I created an array where I pushed all these three variables in. In my HTML template, I am using a table. I tried using *ngFor but it is not working, and also attempted string interpolation which also did not work. Currently, I ...

Troubleshooting Angular 2 component routing issues with a malfunctioning this.router.navigate operation

Struggling with implementing routing in an Angular 2 app based on certain conditions. I am using this.router.navigate method but encountering the "Cannot read property 'navigate' of undefined" error consistently. Any assistance would be greatly a ...

Tips on creating a unit test for validating errors with checkboxes in your code base

In a certain scenario, I need to display an error message when a user clicks on the Next button without agreeing to the terms. To achieve this, I am looking to write a unit test case using Jest and React Testing Library. How can I go about doing this? im ...

Upon completing the installation of the @angular/cli@latest node module, the ng file was unexpectedly missing

I'm currently working on Git Bash on my Windows 10 machine. The command I used was: npm install --save @angular/cli@latest Here is the result: + @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bad9d6d3fa8b899488 ...

Navigating the upgrade of Ag-Grid from version 21 to version 22 within an Angular 8 environment

Recently, Ag-Grid made significant changes to their code in version 22 by deploying it into modules, primarily from the new packages @ag-grid-community/all-modules or @ag-grid-enterprise/all-modules. However, the documentation on their website is quite unc ...

Show the content of a file stored as blob data in an Oracle database using Angular and

Greetings to the Stack Overflow community! Please bear with me if I have omitted any important details in my query. Here's what I need: I currently have a variety of files (pdf, jpg, HTML, CSV, etc) stored as BLOB data in an Oracle database. I'v ...

RxJS: when combined with timer, groupBy operator does not emit any values

Just starting out with RxJS version 6.5.5, I'm encountering an issue with the groupBy operator. Here's a simplified example to showcase the problem. I have a function called retrieveFiles() that retrieves an array of strings. function async ret ...

What benefits does invoking the .call() method on Observable functions offer?

I am new to Angular and finding it challenging to comprehend some code I came across in the ng-bootstrap project. You can find the source code here. The section that particularly confuses me is the ngOnInit method: ngOnInit(): void { const inputValue ...

Having trouble getting dynamic values to render properly in Ionic select? Find a solution in Ionic 4

Encountering an issue with Ionic 4 and ion-select. The problem arises when attempting to bind data, specifically when preselecting data. In this scenario, the ion-select element fails to render properly. <ion-item class="transparent"> ...

Annotating Vue Computed Properties with TypeScript: A Step-by-Step Guide

My vue code looks like this: const chosenWallet = computed({ get() { return return wallet.value ? wallet.value!.name : null; }, set(newVal: WalletName) {} } An error is being thrown with the following message: TS2769: No overload ...

What are the steps to incorporate SignalR into a TypeScript project?

Working on an asp.net mvc 4.5 project with typescript in the client side, I successfully installed and configured signalR on the server side. To integrate it into my project, I also installed signalr.TypeScript.DefinitelyTyped with jquery. In my typescrip ...

Unable to reduce zone.js version in Angular

I'm facing an issue trying to downgrade my zone.js file from version 0.8.10 to 0.8.5 in order to address app problems on older devices like Huawei with Android 5.1.1. Steps I've followed: npm install <a href="/cdn-cgi/l/email-protection" cla ...

Angular 2 template is nowhere to be found

As a newcomer to Angular 2, I am currently developing an app where I have successfully completed the Root component containing a navigation bar and footer. However, as I delve into working on the homepage module, I encountered an error. [Error] Unhandle ...

Using static methods within a static class to achieve method overloading in Typescript

I have a TypeScript static class that converts key-value pairs to strings. The values can be boolean, number, or string, but I want them all to end up as strings with specific implementations. [{ key: "key1", value: false }, { key: "key2&qu ...

Capturing data in JSON format using ng-model for form values

I need help with a form element in my HTML. <form [formGroup]="myForm" (ngSubmit)="searchIncident()"> <select class="form-control" id="category" (change)="getSubCategories($event.target.value)" (ngModel)= ...

Can one generate an enum based on a specific type?

I have a preference: preference Preference = 'OptionA' | 'OptionB' Is it feasible to generate an enumeration from this preference? For instance: enumeration Enum = { OptionA, OptionB } I am uncertain about the feasibility of this. ...