alloisxp
alloisxp

Reputation: 183

HttpInterceptor does not intercept

I'm trying to implement a http-Interceptor, but actually it's not working and I dont understand why. The code follows, first a little bit of explanation:

The http.get in the service goes nowhere (so there should be an error or? This is what I want to use the Interceptor for: Logging production errors.)

I thought the algo trys to send the request, then the interceptor jumps in, pipe and then tap and/or(?) finalize are active and I see something on the console. But nothing happens.

Interceptor:

import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap, finalize } from 'rxjs/operators';

export class HttpErrorInterceptor implements HttpInterceptor{
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log("INTERCEPT");
        return next.handle(req).pipe(
            tap(ev => {
                console.log("TAP");
            }),
            finalize(() => {
                console.log("FINALIZE");
            })

        );
    }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HttpErrorInterceptor } from './http-error.interceptor';
import { HTTP_INTERCEPTORS, HttpClientModule  } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule 
  ],
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: HttpErrorInterceptor,
    multi: true
  }],
  bootstrap: [AppComponent]
})
export class AppModule { }

test.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class TestService {


  private apiUrl = 'https://localhost:8080/api/users';

  constructor(private http: HttpClient) { }

  getUsers(): Observable<String[]> {
    return this.http.get<String[]>(this.apiUrl)
  }
}

and app.component.ts

import { Component } from '@angular/core';
import { TestService } from './test.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'errorHandling';

  constructor(private test: TestService){}

  ngOnInit(){
    console.log("INIT");
    this.test.getUsers();
  }
}

Upvotes: 0

Views: 249

Answers (1)

robert
robert

Reputation: 6142

You need to call subscribe on your TestService getUsers() method. Otherwise no call will be made.

Change this line:

this.test.getUsers();

To this:

this.test.getUsers().subscribe();

Check the docs here

Upvotes: 1

Related Questions