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));
}
}
- angular4 服务依赖注入的三种方法
- angular4基础之服务与依赖注入
- Angular4中的依赖注入
- Spring依赖注入的三种方式详解之三:工厂方法注入
- spring Ioc 依赖注入的三种方式:构造函数注入、setter方法注入和接口注入
- Spring依赖注入的三种方式详解之二:构造方法注入
- 依赖注入的三种实现类型
- spring依赖注入的三种方式
- Spring依赖注入的三种方式
- Spring依赖注入的三种方式
- Spring依赖注入的三种方式
- Spring依赖注入的三种方式
- Spring依赖注入的三种方式
- Spring 依赖注入的三种形式
- 依赖注入的三种实现形式
- Spring的三种依赖注入方式
- Android 的三种依赖注入库
- 依赖注入的三种方式
- 20170928_二叉树的一些基本概念
- OWB的ETL工具教程
- 二叉树的镜像
- css 清除浮动
- LinuxStudyNote(33)-Linux常用命令(8)-mount挂载命令、umount卸载命令
- angular4 服务依赖注入的三种方法
- linux常用操作命令及linux系统目录结构
- [agc015e]Mr.Aoki Incubator
- python笔记003--python的运行方式
- HDU
- 享元模式
- 这是我的第一个博客
- 数据结构实验之链表一:顺序建立链表
- 安装Ubuntu Linux系统时硬盘分区最合理的方法