rxjs - 无法从Interceptor订阅数据

标签 rxjs angular6 interceptor angular-httpclient rxjs6

在我的AppComponent.ts文件中,我使用 HttpClient 进行了 HTTP GET 调用。

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);
    });
  }
}

然后我还有一个拦截器,它拦截 Http 调用并返回一些静态数据(例如缓存)。

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({});
    }
}

但是AppComponent.ts中的订阅文件,没有收到任何回复。事实上,订阅成功或错误函数甚至没有被命中。 也没有控制台错误。有人知道这里发生了什么吗?

注意 我已将返回类型从 Observable<HttpEvent<any>> 更改为至Observable<any>因为 TypeScript 无法转换 Observable<{}>Observable<HttpEvent<any>> .

最佳答案

您的缓存响应类型必须为 HttpResonse ,但更准确地说,它需要是 HttpEvent 类型,其中包括类 HttpResponse<T> :

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

return of(response);

这有点未经测试,不确定 body 是否需要是可解析的 json 字符串才能使其工作:body: '{}' ,但这需要你去尝试。 :)

关于rxjs - 无法从Interceptor订阅数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52774929/

相关文章:

scala - 如何记录所有未过滤的请求

angular - 为什么我的 RxJS 订阅错误处理程序没有触发?

javascript - HTML5 : Attributes are not recognized after being added with JS/Jquery

html - Angular 6 Material - 使用组件时使用了哪些类

bootstrap-4 - 如何为angular 6 bootstrap 4 modal做 Jasmine 单元测试用例

ejb-3.0 - 在方法调用之后使用EJB拦截器

jakarta-ee - ejb 拦截器可以在调用类获取之前更改方法的返回值吗?

angular - 如何等待 observable 的第二个值

angular - 如何使用 RXJS 取消内部 HTTP 可观察的待处理请求?

typescript - 按顺序在 observables 中执行