簡體   English   中英

在Aurelia中注入使用fetch HttpClient的多個類

[英]Inject multiple classes that use the fetch HttpClient in Aurelia

我有一個稱為Infrastructure的類,我認為從HttpClient繼承該類很方便。 此類公開獲取,發布,放置和刪除的方法。

import {Aurelia} from "aurelia-framework";
import {HttpClient, json} from "aurelia-fetch-client";

export default class Infrastructure extends HttpClient {
    get(url, queryString, contentType) {
        //..
    }

    post(url, data, contentType) {
        //..
    }

    put(url, data, contentType) {
        //..
    }

    delete(url, contentType) {
        //..
    }
}

我的想法是,我現在可以擁有注入Infrastructure服務,它們可以在基礎架構上調用configure

import {inject} from "aurelia-framework";
import Infrastructure from "./infrastructure";

@inject(Infrastructure)
export class InventoryService {
    constructor (infrastructure) {

        infrastructure.configure(config => {
            config
                .useStandardConfiguration()
                .withBaseUrl(`http://localhost:64441/inventory`);
        });

        this.infrastructure = infrastructure;
    }
}

我有一些使用Infrastructure的服務,並且一切正常。 問題是我不需要將兩個這樣的服務注入到同一類中,並且配置的baseUrl會相互干擾。

我知道,在Aurelia中,默認情況下一切都是單例,但是在Aurelia中處理這種情況的首選方式是什么?

我知道我總是可以跳過配置baseUrl ,但是能夠進行配置非常方便,我很好奇是否有更好的方法。

您可以使用不同的鍵來注冊同一“類”的多個實例。 注冊鍵可以是任何東西,而不必是類/構造函數。

下面是一個例子。 第一步是將Infrastructure類更改為在構造函數中接受baseUrl參數:

export class Infrastructure {
  constructor(baseUrl) {
    this.configure(config => {
      config
        .useStandardConfiguration()
        .withBaseUrl(baseUrl);
      });
  }
  ...
}

接下來,您需要使用不同的Infrastructure實例配置容器。 以下代碼通常在啟動時發生,也許在main.js

// configure the container
container.registerInstance("Inventory", new Infrastructure("http://foo.com"));
container.registerInstance("Orders", new Infrastructure("http://bar.com"));

現在,您將可以通過鍵解析這些實例:

// resolve by name
var inventory = container.get("Inventory");
var orders = container.get("Orders");

或者使用@inject它們聲明為依賴@inject

import {inject} from "aurelia-framework";

@inject("Inventory", "Orders")
export class InventoryService {
  constructor (inventory, orders) {
    this.inventory = inventory;
    this.orders = orders;
  }
}

在本期中,有很多關於您的情況的討論: https : //github.com/aurelia/dependency-injection/issues/73

暫無
暫無

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

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