i inject implementation of interface ionic2 component (ionic2 beta 10, uses angular2 rc4). lets have following service:
export interface serviceinterface { /*...*/ } @injectable() export class serviceimpl implements serviceinterface { /*...*/ }
how inject ionic2 component? have tried:
import { component, provide, provider } '@angular/core'; import { serviceinterface } './service.interface'; import { serviceimpl } './service.impl'; @component({ providers: [ // exception: can't resolve parameters 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' - though referenced {provide: serviceinterface, useclass: serviceimpl} ] }) export class somecomponent { constructor(private service: serviceinterface) {} }
simply using serviceimpl
follows works fine, not want:
@component({providers: [serviceimpl]}) export class somecomponent { constructor(private service: serviceimpl) {} }
any ideas missing?
in typescript, interfaces not retained @ runtime (they gone), cannot find name 'serviceinterface'
error.
when use
{provide: serviceinterface, useclass: serviceimpl}
the provide
part token. using non-existing token (the interface). possible workaround use string token instead.
another possible way use opaquetoken
instead of string. declare 1 same name interface. here's how done:
import { component, injectable, provide, provider, opaquetoken, inject } '@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 }
see demo plunker.
Comments
Post a Comment