学习目录
前言
之前的一篇文章已经介绍了Angular 4 依赖注入的基础知识,下面将介绍Angular 4依赖注入之组件服务注入的相关内容,分享出来供大家参考学习,下面来来看看详细的介绍:
本系列教程的开发环境及开发语言:
Angular 4 + Angular CLI TypeScript基础知识
如何创建 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']; }}
组件中注入服务
介绍完基础知识,接下来我们来创建一个新的组件 - HeroComponent,它用来显示英雄的信息,具体实现如下:
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' } ]; }}
在 HeroComponent 组件中,我们在 ngOnInit 钩子中进行数据初始化,然后利用 ngFor
指令来显示英雄列表的信息。创建完 HeroComponent 组件,我们要来验证一下该组件的功能。
首先在 AppModule 中导入 HeroComponent 组件,具体如下:
import { HeroComponent } from './hero/hero.component';@NgModule({ declarations: [ AppComponent, HeroComponent ], ...})export class AppModule { }
然后更新一下 AppComponent 组件,具体如下:
import { Component } from '@angular/core';@Component({ selector: 'app-root', template: ` <app-hero></app-hero> `})export class AppComponent {}
如果不出意外的话,访问 http://localhost:4200/
页面,您将看到如下信息:
ID: 11 - Name: Mr. NiceID: 12 - Name: NarcoID: 13 - Name: BombastoID: 14 - Name: CeleritasID: 15 - Name: Magneta
新闻热点
疑难解答
图片精选