簡體   English   中英

實例化對象時Aurelia依賴注入

[英]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實現,但我相信你需要改變的只是constructortype

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM