Angular 2注入复杂的服务

时间:2016-03-28 09:02:38

标签: typescript angular angular2-directives angular2-services

我有三个服务和一个组件:

  • $.ajax({ type: 'POST', url: path, cache: false, data: postData, dataType: 'json', //<-----add this here success: function(result) { for (o in result) { // <----and just use this way console.info(o.city); } }, error: function(e) { $("#sys_msg").html(e); $("#myModal").modal({ show: true, backdrop: false, keyboard: true }); } });
  • root.service
  • abstarct-child.service
  • extend-child.service

使用依赖注入app.component注入root.service,如下所示:

abstarct-child.service

import {Injectable} from 'angular2/core'; import {AbstractChildService} from './abstarct-child.service'; @Injectable() export class RootService { constructor(private _abstractChildService: AbstractChildService) {} UseChildServiceDoSomethingFunction(){} } 看起来像这样:

abstarct-child.service

import {Injectable} from 'angular2/core'; @Injectable() export abstract class AbstractChildService { abstract doSomething(): any ; } 看起来像这样:

extend-child.service

import {Injectable} from 'angular2/core'; import {AbstractChildService} from './abstarct-child.service'; @Injectable() export class ExtendChildService extends AbstractChildService{ constructor(private _num: number) { super(); } doSomething() : any { return true; } } 提供app.componentroot.service extend-child.service,如下所示:

abstract-child.service

我想知道如何向import {Component} from 'angular2/core'; import {Input} from 'angular2/core'; import {provide} from 'angular2/core'; import {RootService} from './root.service'; import {AbstractChildService} from './abstarct-child.service'; import {ExtendChildService} from './extend-child.service'; @Component({ selector: 'app', providers: [provide(AbstractChildService, { useClass: ExtendChildService, useValue: this.num})] }) export class AppComponent { @Input('given_Num') num: number; } 对象注入,在这种情况下是extend-child.service的{​​{1}}?

有人能找到我做错的事吗?

感谢。

1 个答案:

答案 0 :(得分:2)

我还没有完全弄明白你想要完成什么,但是

   provide(AbstractChildService, { 
       useClass: ExtendChildService, 
       useValue: this.num})

不是有效的提供者。

您不能在一个提供商中拥有useClass useValue参数,一次只能有一个。

您也无法在this.装饰器中的提供程序中使用@Component()。在评估装饰器时,还没有this.可以引用的组件实例。

如果您想提供一个号码,可以使用字符串或OpaqueToken

provide('MyNumber', {useValue: 10}),

并通过

注入
constructor(@Inject('MyNumber') private _num: number) { super(); }

另一种方法是使用工厂

provide(ExtendedChildService, {useFactory: () => { new ExtendedChildService(10)});

但仍然无法引用this.

相关问题