依赖注入 – 实例化对象时的Aurelia依赖注入

前端之家收集整理的这篇文章主要介绍了依赖注入 – 实例化对象时的Aurelia依赖注入前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我创建一个支持类,例如具有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); 
    }
}

解决方法

处理此问题的正确方法是使用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 questionofficial docs中给出的答案.

猜你在找的设计模式相关文章