【问题标题】:'HttpInterceptor' only refers to a type, but is being used as a value here'HttpInterceptor' 仅指一种类型,但在此处用作值
【发布时间】:2018-03-31 00:51:25
【问题描述】:

我将新的 VS2017 angular 项目从原来的 4.2.5 升级到 v4.4.6,然后尝试在我的 app.module.shared.ts 文件中设置HttpInterceptor,如下所示:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { HttpClient, HttpInterceptor } from '@angular/common/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './components/app/app.component';
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';

@NgModule({
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        HomeComponent
    ],
    imports: [
        CommonModule,
        HttpModule,
        FormsModule,
        ReactiveFormsModule,
        HttpClient,
        HttpInterceptor,
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ]
})
export class AppModuleShared {
}

VS 已将第 5 行的 HttpInterceptor 导入命令灰显,并在第 28 行记录了一个错误,我在导入列表中调用了 HttpInterceptor。鼠标悬停在红色波浪线上会显示错误消息“(TS) 'HttpInterceptor' 仅指一种类型,但在此处用作值。”

我做错了什么?这基本上是一个原始的、开箱即用的 Angular 实例,基于最新的 VS2017 模板,我唯一做的就是更新 angular 并运行 webpack 的东西。

【问题讨论】:

    标签: angular visual-studio-2017 angular-http-interceptors


    【解决方案1】:

    HttpInterceptor 是一个接口,但“imports”部分等待一个类。

    编辑:据我所知,上面的解释不太清楚,简而言之:

    根据https://angular.io/api/common/http/HttpInterceptor

    HttpInterceptor 是一个接口

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

    我们必须创建一个实现此接口的类并将其放入导入中,而不是将接口放入“imports: [...]”,例如:

    @Injectable()
    export class AppHttpInterceptor implements HttpInterceptor { 
            // bla bla bla
    }
    

    然后

    imports: [
    ...,
    AppHttpInterceptor,
    ...
    ]
    

    【讨论】:

    • 这可能是我在 SO 上看到的最神秘的解释
    • @ManuChadha 感谢您的评论,我在回答中添加了更多信息,希望现在更清楚!
    • 现在好多了:)
    猜你喜欢
    • 2018-08-07
    • 2020-04-28
    • 2021-08-23
    • 2020-12-05
    • 1970-01-01
    • 2023-04-03
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多