我刚刚开始使用adonisjs和nodejs,但在弄清楚如何处理依赖注入时遇到了麻烦。
我使用Laravel已经有一段时间了,我知道adonisjs从中得到了很多启发。但是,我还没有找到处理类中依赖项注入的最佳方法。我尝试创建一个di.js文件来绑定依赖项,但无法在我的类中使用它们。 https://adonisjs.com/docs/4.1/ioc-container
HttpRequestHelper.js
'use strict';
const axios = require('axios');
class HttpRequestHelper {
async get (url) {
return await axios.get(url);
}
}
module.exports = HttpRequestHelper;
di.js
'use strict';
const { ioc } = require('@adonisjs/fold');
const HttpRequestHelper =
require('../app/Utilities/HttpRequestHelper.js');
ioc.singleton('HttpRequestHelper', () => {
return new HttpRequestHelper();
});
TestController.js
'use strict';
const axios = require('axios');
// const HttpRequestHelper = use('HttpRequestHelper');
class TestController {
constructor(HttpRequestHelper) {
this.httpRequestHelper = HttpRequestHelper;
}
async testRoute ({ request, response }) {
let films = this.httpRequestHelper.get('https://swapi.co/api/films');
response.json(films.data);
}
}
module.exports = TestController;
当我尝试访问HttpRequestHelper类中的get函数时,出现Cannot read property 'get' of undefined
错误,这告诉我HttpRequestHelper类未解决。