組件服務(wù)注入

2018-06-06 08:26 更新

閱讀須知

本系列教程的開發(fā)環(huán)境及開發(fā)語言:

基礎(chǔ)知識

如何創(chuàng)建 Angular 組件

在 Angular 中我們通過以下方式創(chuàng)建一個簡單的組件:

  1. @Component({
  2. selector: 'app-root',
  3. template: `
  4. <h1>{{title}}</h1>
  5. `
  6. })
  7. export class AppComponent {
  8. title: string = 'App Works';
  9. }

如何創(chuàng)建 Angular 服務(wù)

在 Angular 中我們通過以下方式創(chuàng)建一個簡單的服務(wù):

  1. export class DataService {
  2. getData() {
  3. return ['Angular', 'React', 'Vue'];
  4. }
  5. }

組件中注入服務(wù)

介紹完基礎(chǔ)知識,接下來我們來創(chuàng)建一個新的組件 - HeroComponent,它用來顯示英雄的信息,具體實現(xiàn)如下:

  1. import { Component, OnInit } from '@angular/core';
  2. @Component({
  3. selector: 'app-hero',
  4. template: `
  5. <ul>
  6. <li *ngFor="let hero of heros">
  7. ID: {{hero.id}} - Name: {{hero.name}}
  8. </li>
  9. </ul>
  10. `
  11. })
  12. export class HeroComponent implements OnInit {
  13. heros: Array<{ id: number; name: string }>;
  14. ngOnInit() {
  15. this.heros = [
  16. { id: 11, name: 'Mr. Nice' },
  17. { id: 12, name: 'Narco' },
  18. { id: 13, name: 'Bombasto' },
  19. { id: 14, name: 'Celeritas' },
  20. { id: 15, name: 'Magneta' }
  21. ];
  22. }
  23. }

HeroComponent 組件中,我們在 ngOnInit 鉤子中進行數(shù)據(jù)初始化,然后利用 ngFor 指令來顯示英雄列表的信息。創(chuàng)建完 HeroComponent 組件,我們要來驗證一下該組件的功能。首先在 AppModule 中導(dǎo)入 HeroComponent 組件,具體如下:

  1. import { HeroComponent } from './hero/hero.component';
  2. @NgModule({
  3. declarations: [
  4. AppComponent,
  5. HeroComponent
  6. ],
  7. ...
  8. })
  9. export class AppModule { }

然后更新一下 AppComponent 組件,具體如下:

  1. import { Component } from '@angular/core';
  2. @Component({
  3. selector: 'app-root',
  4. template: `
  5. <app-hero></app-hero>
  6. `
  7. })
  8. export class AppComponent {}

如果不出意外的話,訪問 http://localhost:4200/ 頁面,您將看到如下信息:

  1. ID: 11 - Name: Mr. Nice
  2. ID: 12 - Name: Narco
  3. ID: 13 - Name: Bombasto
  4. ID: 14 - Name: Celeritas
  5. ID: 15 - Name: Magneta

難道一切就這么結(jié)束了,No! No!別忘記了我們這節(jié)課的主題是介紹如何在組件中注入服務(wù)。在目前的 HeroComponent 組件,我們的英雄列表信息是固定的,在實際的開發(fā)場景中,一般需要從遠(yuǎn)程服務(wù)器獲取相應(yīng)的信息。但我們暫不考慮這個問題,假設(shè)另外一個組件也需要利用同樣的英雄列表信息,那我們要怎么辦,難道直接上 "終極絕招" - Copy && Paste 。當(dāng)然這是 "終極絕招",豈能隨便使用 (不怕被群毆的話,請自便哈)。

針對上面提到的問題,理想的方式是創(chuàng)建一個 HeroService 服務(wù),從而實現(xiàn)數(shù)據(jù)共享。說干就干,我們馬上來創(chuàng)建 HeroService 服務(wù),具體如下:

  1. export class HeroService {
  2. heros: Array<{ id: number; name: string }> = [
  3. { id: 11, name: 'Mr. Nice' },
  4. { id: 12, name: 'Narco' },
  5. { id: 13, name: 'Bombasto' },
  6. { id: 14, name: 'Celeritas' },
  7. { id: 15, name: 'Magneta' }
  8. ];
  9. getHeros() {
  10. return this.heros;
  11. }
  12. }

HeroService 服務(wù)中,我們定義了一個 heros 屬性和一個 getHeros() 方法:

  • heros - 用于保存英雄的列表信息
  • getHeros() - 用于獲取英雄的列表信息

創(chuàng)建完 HeroService 服務(wù)后,接下來我們來介紹如何在組件中使用 HeroService 服務(wù)。

組件中使用 HeroService

組件中使用 HeroService 服務(wù),主要分為三個步驟:

  • 導(dǎo)入 HeroService 服務(wù)

  1. import { HeroService } from '../hero.service';

  • 聲明 HeroService 服務(wù)

  1. @Component({
  2. selector: 'app-hero',
  3. ...
  4. providers: [HeroService]
  5. })

  • 注入 HeroService 服務(wù)

  1. export class HeroComponent implements OnInit {
  2. constructor(private heroService: HeroService) { }
  3. }

完整代碼如下:

  1. import { Component, OnInit } from '@angular/core';
  2. import { HeroService } from '../hero.service';
  3. @Component({
  4. selector: 'app-hero',
  5. template: `
  6. <ul>
  7. <li *ngFor="let hero of heros">
  8. ID: {{hero.id}} - Name: {{hero.name}}
  9. </li>
  10. </ul>
  11. `,
  12. providers: [HeroService]
  13. })
  14. export class HeroComponent implements OnInit {
  15. constructor(private heroService: HeroService) { }
  16. heros: Array<{ id: number; name: string }>;
  17. ngOnInit() {
  18. this.heros = this.heroService.getHeros();
  19. }
  20. }

看到 providers: [HeroService] 這一行,相信有一些讀者會有一些困惑,因為他們可能是按照下面的方式去配置 HeroService 服務(wù)。

  1. @NgModule({
  2. declarations: [
  3. AppComponent,
  4. HeroComponent
  5. ],
  6. ...
  7. providers: [HeroService],
  8. bootstrap: [AppComponent]
  9. })
  10. export class AppModule { }

當(dāng)然兩種方式不會影響,我們最終要實現(xiàn)的功能,但這兩種方式肯定是有區(qū)別的,希望有興趣的讀者,去思考一下哈。在多數(shù)場景下,推薦在 NgModule 的 Metadata 信息中配置相應(yīng)的服務(wù)。

我有話說

為什么配置完 HeroService ,在 HeroComponent 組件類的構(gòu)造函數(shù)中還得進行類型聲明?

  1. import { HeroService } from '../hero.service';
  2. export class HeroComponent implements OnInit {
  3. constructor(private heroService: HeroService) { }
  4. }

其實在 @NgModule({...})@Component({...}) Metadata 中我們只是配置 Provider 的相關(guān)信息,即告訴 Angular DI (依賴注入) 系統(tǒng),如何創(chuàng)建根據(jù)配置的 provider 信息,創(chuàng)建相應(yīng)的依賴對象。而在 HeroComponent 組件類中,我們通過構(gòu)造注入的方式去告訴 Angular DI 系統(tǒng),我們需要的依賴對象類型。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號