国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Angular 4依賴注入學習教程之組件服務注入(二)

2024-05-06 15:16:22
字體:
來源:轉載
供稿:網友

學習目錄

Angular 4 依賴注入教程之一 依賴注入簡介 Angular 4 依賴注入教程之二 組件服務注入 Angular 4 依賴注入教程之三 ClassProvider的使用 Angular 4 依賴注入教程之四 FactoryProvider的使用 Angular 4 依賴注入教程之五 FactoryProvider配置依賴對象 Angular 4 依賴注入教程之六 Injectable 裝飾器 Angular 4 依賴注入教程之七 ValueProvider的使用 Angular 4 依賴注入教程之八 InjectToken的使用

前言

之前的一篇文章已經介紹了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            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 利辛县| 和平区| 祁连县| 二连浩特市| 濮阳市| 民权县| 宣化县| 建湖县| 西乡县| 文化| 浮梁县| 仪陇县| 宣恩县| 古蔺县| 华容县| 江西省| 佳木斯市| 察隅县| 襄樊市| 门头沟区| 合肥市| 咸阳市| 三河市| 西华县| 海原县| 田东县| 墨玉县| 禄丰县| 丹寨县| 灌云县| 泗阳县| 马关县| 岳阳市| 通许县| 长岭县| 台南市| 黄骅市| 肇源县| 沂源县| 社旗县| 吉安县|