Sandy
Sandy

Reputation: 11687

Unable to subscribe data from Interceptor

In my AppComponent.ts file, I made a HTTP GET call using HttpClient.

import { Component } from '@angular/core';
import { Observable, Subscriber, Unsubscribable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

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

  constructor(private httpClient: HttpClient) {

    httpClient.get("").subscribe((response) => {
      console.log(response);
    });
  }
}

Then I also have an interceptor which intercepts the Http call and returns some static data (lets say cache for an example).

import { Injectable } from "@angular/core";
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable, of } from "rxjs";

@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<any> {
        return of({});
    }
}

However the subscription in AppComponent.ts file, doesn't receive any response. In fact the subscribe success or error function doesn't even gets hit. There are no console errors either. Anyone have any idea what is going on here?

NOTE I have changed the return type from Observable<HttpEvent<any>> to Observable<any> as TypeScript wasn't able to cast Observable<{}> to Observable<HttpEvent<any>>.

Upvotes: 2

Views: 502

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71911

Your cached response needs to be of type HttpResonse, but to be more precise, it needs to be of type HttpEvent, which includes the class HttpResponse<T>:

const response = new HttpResponse<object>({
  body: {},
  status: 200
})

return of(response);

This is kinda untested though, not sure if body needs to be a parsable json string to make it work so: body: '{}', but that's for you to try. :)

Upvotes: 2

Related Questions