[英]Aurelia dependency injection when instantiating objects
如果我创建一个支持类,例如将HttpClient注入其中的UserList,那么实例化该类的任何人都必须在构造函数中将HttpClient对象传递给它。 不应该@inject(HttpClient)负责获取HttpClient单例并将其注入构造函数中吗? 否则,每个需要引用UserList的类也将获得对HttpClient的引用,以便它可以将其传递给UserList构造函数(并且无法实现注入的目的)。
UserList.ts
@inject(HttpClient)
export class UserList {
constructor(public http: HttpClient){
}
...
}
DoSomething.ts
export class DoSomething {
userList: UserList;
constructor(){
this.userList = new UserList(); //doesn't work without passing HttpClient
}
}
为了完成这项工作,我必须在DoSomething类中获得对HttpClient的引用,即使它不会直接使用它。 似乎执行不力的工作版本:
DoSomething.ts
@inject(HttpClient)
export class DoSomething {
userList: UserList;
constructor(public http: HttpClient){
this.userList = new UserList(http);
}
}
如果你使用打字稿,不要担心这个。 使用@autoinject看看魔法发生了!
像这样:
import {autoinject} from 'aurelia-framework';
@autoinject()
export class UserList {
constructor(private http: HttpClient){
}
...
}
在其他文件中:
import {autoinject} from 'aurelia-framework';
@autoinject()
export class DoSomething {
constructor(private userList: UserList){
}
}
TypeScript编译器将发出类型元数据,Aurelia将以正确的方式读取此注入实例!
有关以下内容的更多信息: http : //aurelia.io/docs.html#/aurelia/dependency-injection/1.0.0-beta.1.2.3/doc/article/dependency-injection-basics
处理此问题的正确方法是使用Factory
Resolver
import { Factory } from 'aurelia-framework';
@inject(Factory.of(UserList))
export class DoSomething {
userList: UserList;
constructor(UserList) {
// this is a factory, so you call the function without new
this.userList = UserList();
}
}
@inject(HttpClient)
export class UserList {
http: HttpClient;
constructor(HttpClient) {
this.http = HttpClient;
}
}
您需要在DoSomething中注入UserList
import {UserList} from 'where-ever-user-list-is';
import {inject} from 'aurelia-framework';
@inject(UserList)
export class DoSomething {
userList: UserList;
constructor(userList){
this.userList = userList
}
}
如果要使用Aurelia dependency injection
,则需要导入所需的模块:
import {HttpClient} from 'aurelia-fetch-client';
import {inject} from 'aurelia-framework';
@inject(HttpClient)
export class DoSomething{
constructor(http){
// do your stuff
}
}
这是我使用的ES6实现,但我相信你需要改变的只是constructor
的type
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.