如果我创建一个支持类,例如具有HttpClient的UserList将其注入其中,然后无论谁实例化该类都必须在构造函数中将HttpClient对象传递给它.不应该@inject(HttpClient)负责获取HttpClient单例并将其注入
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); } }处理此问题的正确方法是使用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; } }
有关详细信息,请参阅此related question或official docs中给出的答案.