微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

是否可以注入与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 })
  ]);

但以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; };
}

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

import {Injectable} from 'angular2/core';
import {Course} from './Course.class';
@Injectable()
export class CoursesServiceInterface {  
    getAllCourses() : Promise<Course[]> { return null; };
    getCourse(id: number) :Promise<Course> { return null; };
    remove (id: number) : Promise<{}> { return null; };
}
否,DI不支持接口.使用TypeScript接口在运行时不再可用,只能静态地使用,因此不能用作DI令牌.

或者,您可以使用字符串作为键或Opaquetoken

provide('CoursesServiceInterface',{useClass: CoursesServiceMock}) // old
providers: [{provide: 'CoursesServiceInterface',useClass: CoursesServiceMock}]

并注入它

constructor(@Inject('CoursesServiceInterface') private coursesService:CoursesServiceInterface) {}

参见https://angular.io/docs/ts/latest/api/core/index/OpaqueToken-class.html

原文地址:https://www.jb51.cc/angularjs/140822.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐