【问题标题】:Cannot read property 'intercept' of undefined无法读取未定义的属性“拦截”
【发布时间】:2020-07-03 14:45:38
【问题描述】:

我有一个拦截器,我想在 app.module.ts 中作为 const 提供它。所以我使用了一个单独的文件将所有拦截器声明为一个对象数组。

在 http-interceptors/index.ts

import { HTTP_INTERCEPTORS } from "@angular/common/http";
import { ErrorIntercept } from "./error.interceptor";
import { CompanyInfoService } from "../services/companyInfo.service";

export const interceptorProviders = [
{ 'provide': HTTP_INTERCEPTORS, 'useclass': ErrorIntercept, 'multi': true, 'deps': [CompanyInfoService] }
];

在我的 app.module.ts 中,

import {interceptorProviders} from './http-interceptors/';
...
@NgModule ({
    ...
    providers: [interceptorProviders]
})

这会引发错误 - Cannot read property 'intercept' of undefined

但是,当我如下在 app.module.ts 中直接提供拦截器时,它按预期工作。

providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: ErrorIntercept,
    multi: true,
    deps: [CompanyInfoService]
}]

我无法找出原因...所以请告诉我您的想法。蒂亚!

【问题讨论】:

  • 尝试传播你导出的数组

标签: angular angular-httpclient angular-http-interceptors


【解决方案1】:

您可以传播导出的interceptorProviders 数组。因为提供者需要objectclass。但是你提供了一个数组。

您还需要将useclass 更改为useClass

export const interceptorProviders = [
  { 'provide': HTTP_INTERCEPTORS, 'useClass': ErrorIntercept, 'multi': true, 'deps': [CompanyInfoService] }
];
import {interceptorProviders} from './http-interceptors/';

@NgModule ({
   ...
   providers: [...interceptorProviders] // spread the array
})

感谢@alessandro

【讨论】:

  • 嗨,我试过了,但我得到了错误 - Type '{ provide: InjectionToken;使用类:类型错误拦截;多:布尔值;部门:(公司信息服务类型)[]; }[]' 不可分配给类型 'Provider[]'。
  • 编辑了答案。 useClass 而不是 useclass
  • 骆驼案更新对我有用...尽管@SheikAlthaf 我不必使用扩展运算符
  • @Jeyashree.A 很高兴听到
猜你喜欢
  • 2016-07-05
  • 1970-01-01
  • 2014-02-09
  • 1970-01-01
  • 2021-01-06
  • 2020-04-06
  • 2020-10-30
  • 2019-10-09
  • 1970-01-01
相关资源
最近更新 更多