Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了是否可以注入与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

大佬总结

以上是大佬教程为你收集整理的是否可以注入与angular2的界面?全部内容,希望文章能够帮你解决是否可以注入与angular2的界面?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。