Ionic2 DI:为组件提供接口实现

时间:2016-08-01 15:27:43

标签: typescript angular ionic2

我想将一个接口的实现注入Ionic2组件(Ionic2 Beta 10,使用Angular2 RC4)。让我们说我们有以下服务:

<Link to="./">Intro</Link>
<Link to="./news">News</Link>
<Link to="./about">About</Link>

如何将其注入Ionic2组件?我试过了:

export interface ServiceInterface { /*...*/ }
@Injectable()
export class ServiceImpl implements ServiceInterface { /*...*/ }

简单地使用import { Component, provide, Provider } from '@angular/core'; import { ServiceInterface } from './service.interface'; import { ServiceImpl } from './service.impl'; @Component({ providers: [ // Exception: Can't resolve all parameters for SomeComponent: (?) ServiceImpl, // @deprecated - seen on: http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html provide(ServiceInterface, {useClass: ServiceImpl}), // @deprecated - seen on: http://plnkr.co/edit/RSTG86qgmoxCyj9SWPwY?p=preview new Binding(ServiceInterface, {toAlias: ServiceImpl}), // @deprecated - seen on: https://www.dartdocs.org/documentation/angular2/2.0.0-beta.9/angular2/Provider/useClass.html new Provider(ServiceInterface, {useClass: ServiceImpl}), // TS Error: Cannot find name 'ServiceInterface' - even though it is properly referenced {provide: ServiceInterface, useClass: ServiceImpl} ] }) export class SomeComponent { constructor(private service: ServiceInterface) {} } 如下工作完全正常,但这不是我想要的:

ServiceImpl

我缺少什么想法?

1 个答案:

答案 0 :(得分:1)

在TypeScript中,接口不会在运行时保留(它们就会消失),因此Cannot find name 'ServiceInterface'错误。

使用时

{provide: ServiceInterface, useClass: ServiceImpl}

provide部分是一个标记。您现在正在使用不存在的令牌(界面)。可能的解决方法是使用字符串作为标记。

另一种可能的方法是使用OpaqueToken而不是字符串。您可以声明一个与接口名称相同的名称。以下是如何做到的:

import { Component, Injectable, provide, Provider, OpaqueToken, Inject } from '@angular/core';

export interface ServiceInterface { /*...*/ }
@Injectable()
export class ServiceImpl implements ServiceInterface { /*...*/ }

const ServiceInterface = new OpaqueToken("ServiceInterface");  // <----- token defined

@Component({
  selector: 'my-app',
  template: '<h1>My First Angular 2 App</h1>',
  providers: [{provide: ServiceInterface, useClass: ServiceImpl}] // <-- providing
})
export class AppComponent {
    constructor(@Inject(ServiceInterface) private service: ServiceInterface) {}
                        ^^^^^^^^^^^^^^^^-- injecting
}

请参阅demo plunker