【问题标题】:Issue with mocking http => returns observable in Angular 7模拟 http => 在 Angular 7 中返回 observable 的问题
【发布时间】:2019-12-07 07:34:51
【问题描述】:

我的 Angular 应用程序中有一个 HTTP 拦截器,如果调用某个端点而不是实际访问服务器,我想简单地返回模拟数据。

我的可观察代码似乎存在问题,因为我没有收到任何错误,但 .subscribe 函数未执行。我不太确定会发生什么,因为我没有收到任何错误。

HttpInterceptor

import {Injectable} from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {DemoHttpServer} from './demo-http-server';

@Injectable()
export class DemoHttpInterceptor implements HttpInterceptor {

  constructor(private demoHttpServer: DemoHttpServer) {

  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (request.url.startsWith('https://demo.company.com/api/')) {
      return this.demoHttpServer.handle(request);
    }

    return next.handle(request);
  }
}

演示 HTTP 服务器

handle(req: HttpRequest<any>): Observable<any> {
    const result = {isMock: true};

    return Observable.create((observer: Subscriber<any>) => {
      observer.next(result);
      observer.complete();
    });
  }

在我的组件中

http.get('https://demo.company.com/api/counts')
.subscribe(data => {
  // never get in here..., don't get any console errors
})

【问题讨论】:

  • 另外,您使用的是哪个版本的 RxJS?当前的导入应该是这样的:import {Observable} from 'rxjs';
  • 在进一步研究这一点时,observer.next 期望的是一个 Observable,而不是一个简单的对象。看到这个:dev.to/sanidz/…

标签: angular observable angular-http-interceptors


【解决方案1】:

查看你的代码和我在 cmets 中提到的帖子,我构建了一个这样的拦截器:

@Injectable()
export class DemoInterceptor implements HttpInterceptor {

  constructor() { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (req.url.startsWith('https://jsonplaceholder.typicode.com/todos')) {
      const mockToDos = [{
        userId: 1,
        id: 99,
        title: 'test',
        completed: false
      }];

      return of(new HttpResponse({
        status: 200, body: mockToDos
      }));
    }

    return next.handle(req);
  }
}

注意它返回一个Observable&lt;HttpResponse&gt;

您可以在这里找到有效的闪电战:https://stackblitz.com/edit/angular-mock-interceptor-deborahk

对于您的场景,代码看起来更像这样:

    if (req.url.startsWith('https://demo.company.com/api/')) {
      const mockData = mockBody;

      return of(new HttpResponse({
        status: 200, body: mockBody
      }));
    }

【讨论】:

  • 哦,我真是个笨蛋……一天结束了,我的大脑被炸了。谢谢德博拉克!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
  • 2019-06-25
相关资源
最近更新 更多