加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

是否可以注入与angular2的界面?

发布时间:2020-12-17 09:16:19 所属栏目:安全 来源:网络整理
导读:我想知道在Angular2中注入接口是否有正确的方法? (参见下文) 我认为这与接口上缺少的@Injectable()装饰器有关,但似乎这是不允许的. 问候. 当CoursesServiceInterface实现为接口时,TypeScript编译器会抱怨“CoursesServiceInterface找不到名称”: import {C
我想知道在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读