Chỉ trong trường hợp bạn muốn có một phiên bản rút gọn của nhà cung cấp, mọi thứ trở nên phức tạp hơn một chút.
Đây là mã nhà cung cấp:
angular
.module('core.services')
.provider('storageService', [function() {
function isLocalStorageEnabled(window) {
return true;
}
this.$get = ['$window', 'chromeStorageService', 'html5StorageService',
function($window, chromeStorageService, html5StorageService) {
return isLocalStorageEnabled($window) ? html5StorageService : chromeStorageService;
}];
}]);
Các trường hợp thử nghiệm:
describe('Storage.Provider', function() {
var chrome = {engine: 'chrome'};
var html5 = {engine: 'html5'};
var storageService, provider;
beforeEach(module('core.services'));
beforeEach(function() {
module(function (storageServiceProvider) {
provider = storageServiceProvider;
});
});
beforeEach(angular.mock.module(function($provide) {
$provide.value('html5StorageService', html5);
$provide.value('chromeStorageService', chrome);
}));
// the trick is here
beforeEach(inject(function($injector) {
storageService = $injector.invoke(provider.$get);
}));
it('should return Html5 storage service being run in a usual browser', function() {
expect(storageService).toBe(html5);
});
});
Trong trường hợp này $ get là một mảng và bạn không thể chỉ gọi nó như là một chức năng thông thường cung cấp phụ thuộc làm đối số. Giải pháp là sử dụng $ injector.invoke().
Điều kỳ lạ là hầu hết các hướng dẫn và mẫu đều bỏ sót chi tiết này.
Tính năng này hoạt động như thế nào mà không có bất kỳ lệnh gọi 'tiêm' nào? Tôi thấy rằng tôi đã phải làm theo các 'module()' gọi với 'inject()' – Merott
Các tiêm kết thúc tốt đẹp các thử nghiệm (trong nó (...) tuyên bố) –
"Bằng chứng là trong Plunker" Nó didn ' t làm việc, nhưng đã ném rất nhiều lỗi phụ thuộc. – LeeGee