Angular 4 依赖注入教程之二 组件服务注入
目录
阅读须知本系列教程的开发环境及开发语言:
基础知识如何创建 Angular 组件在 Angular 中我们通过以下方式创建一个简单的组件: @Component({
selector: 'app-root',template: `
<h1>{{title}}</h1>
`
})
export class AppComponent {
title: string = 'App Works';
}
如何创建 Angular 服务在 Angular 中我们通过以下方式创建一个简单的服务: export class DataService {
getData() {
return ['Angular','React','Vue'];
}
}
组件中注入服务介绍完基础知识,接下来我们来创建一个新的组件 - import { Component,OnInit } from '@angular/core';
@Component({
selector: 'app-hero',template: `
<ul>
<li *ngFor="let hero of heros">
ID: {{hero.id}} - Name: {{hero.name}}
</li>
</ul>
`
})
export class HeroComponent implements OnInit {
heros: Array<{ id: number; name: string }>;
ngOnInit() {
this.heros = [
{ id: 11,name: 'Mr. Nice' },{ id: 12,name: 'Narco' },{ id: 13,name: 'Bombasto' },{ id: 14,name: 'Celeritas' },{ id: 15,name: 'Magneta' }
];
}
}
在 import { HeroComponent } from './hero/hero.component';
@NgModule({
declarations: [
AppComponent,HeroComponent
],...
})
export class AppModule { }
然后更新一下 import { Component } from '@angular/core';
@Component({
selector: 'app-root',template: `
<app-hero></app-hero>
`
})
export class AppComponent {}
如果不出意外的话,访问 ID: 11 - Name: Mr. Nice ID: 12 - Name: Narco ID: 13 - Name: Bombasto ID: 14 - Name: Celeritas ID: 15 - Name: Magneta 难道一切就这么结束了,No! No!别忘记了我们这节课的主题是介绍如何在组件中注入服务。在目前的 针对上面提到的问题,理想的方式是创建一个 export class HeroService {
heros: Array<{ id: number; name: string }> = [
{ id: 11,name: 'Magneta' }
];
getHeros() {
return this.heros;
}
}
在
创建完 组件中使用 HeroService组件中使用
import { HeroService } from '../hero.service';
@Component({
selector: 'app-hero',...
providers: [HeroService]
})
export class HeroComponent implements OnInit {
constructor(private heroService: HeroService) { }
}
完整代码如下: import { Component,OnInit } from '@angular/core';
import { HeroService } from '../hero.service';
@Component({
selector: 'app-hero',template: `
<ul>
<li *ngFor="let hero of heros">
ID: {{hero.id}} - Name: {{hero.name}}
</li>
</ul>
`,providers: [HeroService]
})
export class HeroComponent implements OnInit {
constructor(private heroService: HeroService) { }
heros: Array<{ id: number; name: string }>;
ngOnInit() {
this.heros = this.heroService.getHeros();
}
}
看到 @NgModule({
declarations: [
AppComponent,...
providers: [HeroService],bootstrap: [AppComponent]
})
export class AppModule { }
当然两种方式不会影响,我们最终要实现的功能,但这两种方式肯定是有区别的,希望有兴趣的读者,去思考一下哈。在多数场景下,推荐在 我有话说为什么配置完
|
