简体   繁体   English

Angular 8 HTTP INTERCEPTOR 中断订阅

[英]Angular 8 HTTP INTERCEPTOR breaks subscribe

I trying to set up an Angular 8 project that allows me to mock api calls with HTTP INTERCEPTORS.我试图建立一个 Angular 8 项目,允许我使用 HTTP 拦截器模拟 api 调用。 The basic idea is if I add a --configuration=mock flag to my ng serve script the interceptor will be injected into my app.module and I'll get data from a JSON file rather than an external API.基本思想是,如果我在我的 ng serve 脚本中添加一个 --configuration=mock 标志,拦截器将被注入到我的 app.module 中,我将从 JSON 文件而不是外部 API 中获取数据。 I'm more or less following this example, https://stackblitz.com/edit/angular-mock-http-interceptor For some reason when I use the interceptor my component's subscription to the data service is broken.我或多或少地遵循这个例子, https://stackblitz.com/edit/angular-mock-http-interceptor由于某种原因,当我使用拦截器时,我的组件对数据服务的订阅被破坏了。 As far as I can tell I'm building the exact same array on the mock service as I do with the live one.据我所知,我正在模拟服务上构建与实时服务完全相同的数组。 can't figure out why it's breaking.无法弄清楚它为什么会破裂。 Here are the getter and the Observable from the service:以下是服务中的 getter 和 Observable:

getUsers() {
    this.http.get<any>('https://jsonplaceholder.typicode.com/users')
    .subscribe(fetchedUsers => {
      this.users = fetchedUsers;
      this.usersUpdated.next([...this.users]);
    });
  }

  getUsersUpdatedListener() {
    return this.usersUpdated.asObservable();
  }

The component calling the service:调用服务的组件:

ngOnInit() {
    this.usersService.getUsers();
    this.usersSub = this.usersService.getUsersUpdatedListener()
    .subscribe((users: User[]) => {
      this.users = users;
    });
  }

and finally the interceptor class:最后是拦截器类:

import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import * as users from '../../assets/mockData/users.json';

const urls = [
  {
      url: 'https://jsonplaceholder.typicode.com/users',
      json: users
  }
];


@Injectable()
export class HttpMockRequestInterceptor implements HttpInterceptor {
    constructor(private injector: Injector) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        for (const element of urls) {
            if (request.url === element.url) {
                console.log('Loaded from json : ' + request.url);
                return of(new HttpResponse({ status: 200, body: ((element.json) as any).default }));
            }
        }
        console.log('Loaded from http call :' + request.url);
        return next.handle(request);
    }
}

The whole project can be viewed here: https://github.com/reynoldsblair/learn-http整个项目可以在这里查看: https : //github.com/reynoldsblair/learn-http

Why is the interceptor breaking my project?为什么拦截器会破坏我的项目?

Dude your interceptor is absolutely fine i just pulled your project and its your user-list.component.ts which is wrong, you are trying to subscribe to the this.usersService.getUsersUpdatedListener() stream after this.usersService.getUsers();伙计,您的拦截器绝对没问题,我刚刚拉了您的项目及其user-list.component.ts ,这是错误的,您正在尝试在this.usersService.getUsers();之后订阅this.usersService.getUsersUpdatedListener()this.usersService.getUsers(); fires which opens you up to a bit of a race condition.火灾让你面临一些竞争条件。 Moving the subscription logic before you call getUsers solved it and works every time on both HttpRequestInterceptor and HttpMockRequestInterceptor在调用getUsers之前移动订阅逻辑解决了它并且每次都在HttpRequestInterceptorHttpMockRequestInterceptor

 ngOnInit() {
    this.usersSub = this.usersService.getUsersUpdatedListener()
      .subscribe((users: User[]) => {
        this.users = users;
      });
    this.usersService.getUsers();
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM