1. 程式人生 > >angular4 服務依賴注入的三種方法

angular4 服務依賴注入的三種方法

假設有服務authservice,現在要把它注入到我們的元件中。有下列三種方法。

方法一:最簡單直接,直接生產一個該服務的例項物件。

import { Component, OnInit } from'@angular/core';

//引入AuthService

import { AuthService } from'../core/auth.service';

@Component({

  selector:'app-login',

  template:`

    <div>

      <input #usernameReftype="text">

      <input #passwordReftype="password">

      <button(click)="onClick(usernameRef.value,passwordRef.value)">Login</button>

    </div>

  `,

  styles: []

})

exportclassLoginComponentimplements OnInit {

//宣告成員變數,其型別為AuthService

  service: AuthService;

constructor() {

this.service =newAuthService();

  }

ngOnInit() {

  }

onClick

(username,password) {

//呼叫service的方法

console.log('auth result is:'+this.service.loginWithCredentials(username, password));

  }

}

方法二:

import { Component, OnInit } from'@angular/core';

import { AuthService } from'../core/auth.service';

@Component({

  selector:'app-login',

  template:`

    <div>

      <input #usernameReftype="text">

      <input #passwordReftype="password">

      <button(click)="onClick(usernameRef.value,passwordRef.value)">Login</button>

    </div>

  `,

  styles: [],

//providers中配置AuthService

  providers:[AuthService]

})

exportclassLoginComponentimplements OnInit {

//在建構函式中將AuthService示例注入到成員變數service

//而且我們不需要顯式宣告成員變數service

constructor(private service: AuthService) {

  }

ngOnInit() {

  }

onClick(username,password) {

console.log('auth result is:'+this.service.loginWithCredentials(username, password));

  }

}

import是要將型別引入進來,而provider裡面會配置這個型別的例項。

方法三:服務在主模組中宣告,元件只是把主模組中的例項物件引用過來。推薦這種方式!

import { Component, OnInit, Inject } from'@angular/core';

@Component({

  selector:'app-login',

  template:`

    <div>

      <input #usernameReftype="text">

      <input #passwordReftype="password">

      <button(click)="onClick(usernameRef.value,passwordRef.value)">Login</button>

    </div>

  `,

  styles: []

})

exportclassLoginComponentimplements OnInit {

constructor(@Inject('auth') private service) {

  }

ngOnInit() {

  }

onClick(username,password) {

console.log('auth result is:'+this.service.loginWithCredentials(username, password));

  }

}