我尝试使用ES6语法将服务导入控制器,但我遇到注入问题
CategoriesService.js
export default class CategoriesService {
constructor() {
this.getCategories = function ($q) {
var deferred = $q.defer();
deferred.resolve([
{
id: '1',
name: 'Category One',
slug: 'category_one',
profile: {
id: '1',
name: 'Thomas Wayne',
location: '1007 Mountain Drive, Gotham',
description: 'Dr. Thomas Wayne, one of the most respected patrons in all of Gotham City',
images: ['...', '...'],
featuredImage: '...'
}
},
{
id: '2',
name: 'Category Two',
slug: 'category_two',
profile: {
id: '2',
name: 'Martha Kane',
location: '1007 Mountain Drive, Gotham',
description: 'Martha Wayne (née Kane) was born into the Kane family, who were so rich that they allegedly "owned the half of Gotham that the Waynes don\'t"',
images: ['...', '...'],
featuredImage: '...'
}
}
]);
return deferred.promise;
}
}
}
CategoriesService.$inject = [];
CategoriesController.js
import CategoriesService from './CategoriesService';
export default class CategoriesController {
constructor(CategoriesService) {
CategoriesService.getCategories().then(getCategoriesSuccessFn, getCategoriesFailFn);
function getCategoriesSuccessFn(data) {
this.categories = data;
}
function getCategoriesFailFn() {
console.error('Something went wrong');
}
}
}
CategoriesController.$inject = ['CategoriesService'];
错误
angular.js:13424 Error: [$injector:unpr] Unknown provider: CategoriesServiceProvider <- CategoriesService
http://errors.angularjs.org/1.5.3/$injector/unpr?p0=CategoriesServiceProvider%20%3C-%20CategoriesService
at angular.js:68
at angular.js:4418
at Object.getService [as get] (angular.js:4571)
at angular.js:4423
at getService (angular.js:4571)
at injectionArgs (angular.js:4595)
at Object.invoke (angular.js:4617)
at $controllerInit (angular.js:10027)
at nodeLinkFn (angular.js:8965)
at angular.js:9362
知道我在这里失踪的是什么吗?
答案 0 :(得分:2)
即使使用ES6导入/导出,您仍然需要注册该服务。
<强> App.js 强>
import CategoriesService from './CategoriesService';
import CategoriesController from './CategoriesController';
angular.module('app', [])
.service('CategoriesService', CategoriesService)
.controller('CategoriesController', CategoriesController);