0

我正在使用 OpaqueToken 将配置对象注入到包含 API 端点等内容的应用程序中。我使用 Angular 文档进行了设置,并且能够将配置 DI 到组件中并检索值。我希望能够对配置进行类型检查,以便它导出组件构造函数在 DI 期间使用的接口,但是如果我将组件构造函数中的类型从更改AppConfigstring不显示错误,即使类型错误...

任何人都知道为什么这不显示类型错误?

APP-CONFIG.TS

import { OpaqueToken } from '@angular/core';

export let APP_CONFIG = new OpaqueToken('app.config');

export interface AppConfig {
  apiEndpoint: string;
}

export const APP_DI_CONFIG: AppConfig = {
  apiEndpoint: 'http://example.dev/api/v1'
};

AUTH.MODULE.TS

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { ReactiveFormsModule } from '@angular/forms';

// Config
import { APP_CONFIG, APP_DI_CONFIG } from '../app-config';

// Components
import { LoginComponent } from './login/login.component';
import { ForgotComponent } from './forgot/forgot.component';
import { ResetComponent } from './reset/reset.component';

// Routing
import { AuthRoutingModule } from './auth-routing.module';

@NgModule({
  imports: [
    // Angular modules
    CommonModule,
    AuthRoutingModule,
    ReactiveFormsModule
  ],
  providers: [
    { provide: APP_CONFIG, useValue: APP_DI_CONFIG }
  ],
  declarations: [
    LoginComponent,
    ForgotComponent,
    ResetComponent
  ]
})
export class AuthModule { }

登录组件.TS

import { Component, OnInit, Inject } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

// Config
import { APP_CONFIG, AppConfig } from '../../app-config';

import { AuthService } from '../../core/auth.service';

@Component({
  selector: 'cf-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  // Data model
  credentials: { username: string, password: string };

  constructor(
    private authService: AuthService,
    private formBuilder: FormBuilder,
    //@Inject(APP_CONFIG) private config: AppConfig // Original
    @Inject(APP_CONFIG) private config: string // Should fail type check?
  ) { }

  ngOnInit(): void {
    console.log(this.config);
  }

}

更新

@JB-nizet 表示 InjectionTokens 在 v4 中使用,尽管在 VSCode 中仍然没有显示类型错误,但它允许在令牌上使用泛型。

import { InjectionToken } from '@angular/core';

export let APP_CONFIG = new InjectionToken<AppConfig>('app.config');

// TODO: get rid of warnings by splitting interface out into separate file
// NOTE: short term solution use a class instead of an interface
// export interface AppConfig {
export class AppConfig {
  apiEndpoint: string;
}

export const APP_DI_CONFIG: AppConfig = {
  apiEndpoint: 'http://example.dev/api/v1'
};
4

1 回答 1

2

JavaScript 在运行时不会强制执行类型约束,因此当 TypeScript 编译为 JS 时,此信息会丢失。

静态分析不会获得有关连接的提供者和构造函数的信息。如果您使用@Inject(APP_CONFIG) private config: string静态分析只是假设传递的值将是一个字符串,并且由于缺乏更准确的信息而坚持使用该信息。

于 2017-03-26T19:57:21.873 回答