angular4 服务依赖注入的三种方法

来源:互联网 发布:阿里云数据分析 编辑:程序博客网 时间:2024/06/05 15:53

假设有服务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));

  }

 

}