Angular2提供的依赖注入的实现
2020-02-21 本文已影响0人
Will_板凳
Angular2提供依赖注入的实现, 主要为两方面
1 可注入的功能组件如何实现;
- 这点主要通过 @Injectable() 装饰器来声明某个类可被注入实例化。 例子:
import { Injectable } from '@angular/core';
@Injectable()
export class HeroService {
constructor() { }
getHeroes(): Hero[] {
return HEROES;
}
}
上面代码把HeroService声明为可注入的服务, 这样就可以在别的组件中通过依赖注入的方式来使用
接下来需要在angular的根模块NgModule的providers中声明这个服务。 比如默认app.module.ts中的AppModule类。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HeroesComponent } from './heroes/heroes.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
import { HeroService } from './hero.service';
import { AppRoutingModule } from './/app-routing.module';
@NgModule({
declarations: [
AppComponent,
HeroesComponent,
HeroDetailComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [HeroService],
bootstrap: [AppComponent]
})
export class AppModule { }
2如何在另外对象中注入别的功能组件
import { HeroService } from '../hero.service';
在该类的构造函数中导入HeroService
constructor(private heroService: HeroService) { }
使用注入组件的函数
getHeroes(): void {
this.heroes = this.heroService.getHeroes();
}