相关疑难解决方法(0)

是否可以使用angular2注入接口?

我想知道是否有一种在Angular2中注入接口的正确方法?(参见下文)

我认为这与接口上缺少的@Injectable()装饰器有关,但似乎不允许这样做.

问候.

当CoursesServiceInterface作为接口实现时,TypeScript编译器会抱怨"CoursesServiceInterface找不到名称":

import {CoursesServiceInterface} from './CoursesService.interface';
import {CoursesService} from './CoursesService.service';
import {CoursesServiceMock} from './CoursesServiceMock.service';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS, 
  GlobalService,
  provide(CoursesServiceInterface, { useClass: CoursesServiceMock })
  ]);
Run Code Online (Sandbox Code Playgroud)

但是使用CoursesServiceInterface作为接口:

import {Injectable} from 'angular2/core';
import {Course} from './Course.class';
//@Injectable()
export interface CoursesServiceInterface {
    getAllCourses(): Promise<Course[]>;//{ return null; };
    getCourse(id: number): Promise<Course>;// { return null; };
    remove(id: number): Promise<{}>;// { return null; };
}
Run Code Online (Sandbox Code Playgroud)

当service是一个类时,TypeScript编译器不再抱怨:

import {Injectable} from 'angular2/core';
import {Course} from './Course.class';
@Injectable()
export class CoursesServiceInterface {  
    getAllCourses() : Promise<Course[]> { return null; …
Run Code Online (Sandbox Code Playgroud)

interface inject angular

52
推荐指数
3
解决办法
3万
查看次数

angular-cli:使用环境变量的条件导入

有没有办法根据angular-cli@1.0.0-beta.16中的环境变量有条件地更改导入?我试图以一种不需要在客户端代码中导入服务的代码更改的方式来实现它,但是在需要时我可以指定一个构建标志来交换模拟服务.

我试过在这篇文章中使用了一种模式:

文件结构:

MyService
    MyServiceMock.ts
    MyServiceReal.ts
    index.ts
Run Code Online (Sandbox Code Playgroud)

在index.ts中,您可以拥有以下内容:

import { environment} from '../environments/environment';

export const MyService = environment.mock ?
    require('./MyServiceMock').MyServiceMock:
    require('./MyServiceReal').MyServiceReal;
Run Code Online (Sandbox Code Playgroud)

在您的客户端代码中,导入MyService:

import MyService from './myservice/index';
Run Code Online (Sandbox Code Playgroud)

页面加载,我可以看到在单步执行代码时注入依赖项,但是编译错误(我认为是TypeScript错误)沿着这一行Cannot find name 'MyService'.

typescript webpack angular-cli angular

9
推荐指数
1
解决办法
7279
查看次数

标签 统计

angular ×2

angular-cli ×1

inject ×1

interface ×1

typescript ×1

webpack ×1