Angular2,注入污染物

时间:2016-03-23 20:01:18

标签: angular2-services angular2-di angular2-injection

我这样做:

import {testInjection} from './ts/models';
import {bootstrap} from 'angular2/platform/browser'; 

bootstrap(AppComponent, [testInjection]).catch(err => console.error(err));

in models.ts

let TEST:string = "test";

export var testInjection: Array<any>=[
    bind(TEST).toValue(TEST)
];

然后在AppComponent中:

class export AppComponent{
constructor(
 public http: Http,
    @Inject(TEST) TEST:string
    ){

  }
}

但是收到此错误:错误TS2304:找不到名称'TEST'。 有人可以指出我做错了什么。

TNX

2 个答案:

答案 0 :(得分:0)

你做错了,做一个服务

import { Injectable } from '@angular/core';

import { testInjection } from './models';

@Injectable()
export class TestService {
  getTestValue() {
    return testInjection;
  }
}

在你的AppComponent中

import {TestService} from './test.service'
class export AppComponent{
constructor(
 public http: Http, _testService : TestService){
     console.log(_testService.getTestValue());
  }
}

在Angular2中,您只需要使用@Injecatable,它应该在服务中使用。在组件中你只需要DI :)。 希望它可以帮到你

答案 1 :(得分:0)

您正在尝试使用模式进行代码检查,仅用于类型检查,如果您正在使用,则不需要使用@inject,

创建单一服务的更好方法,您可以在其中检查类型,调用方法并执行任何操作,现在,如果您要创建服务而不是提供至少一个装饰器,则可以{{1或者您可以使用@Component。像这样 -

@Injectable

或者你也可以这样使用它 -

import { Injectable } from './@angular/core';

@Injectable()
export class TestService {
  name:string =null;
  email:string =null;
 ...///
  constructor(){
   //do your stuff
  }
}
  

PS: - 必须用至少一个装饰器装饰类

现在通过这样做你已经成功创建了一个类,现在如果在多个组件中使用这个类,你可以在这样的引导时注入它 -

import { Component } from './@angular/core';

    @Component({
       selector: 'testService'
    })
    export class TestService {
      name:string =null;
      email:string =null;
     ...///
      constructor(){
       //do your stuff
      }
    }

现在如果你在bootstrap中注入你的服务,你不需要每次都在提供者列表中提供这个,因为angular会自动为每个组件创建这个服务的实例,

但是,如果您在引导时没有注入服务而不是需要导入服务,并且需要注入提供者列表,而不是像这样使用它: -

bootstrap(AppComponent, [TestService]).catch(err => console.error(err));

希望这一点清楚Angular2中有关注射的一些观点。

相关问题