我希望能夠打開和關閉我的angularJS應用程序中的$ httpBackend模擬。
這意味着我想要注入$ httpBackend /懶惰/按需。 能夠打開和關閉它也是很好的。
例如爲從CMS預覽的AngularJS應用程序提供輸入數據。
下面的代碼只有在將ngMockE2E移動到普通的依賴項時才起作用,並且將$ httpBackend注入我的工廠的標準方式。
代碼設置UPP $ httpBackend從一個配置文件中的所有呼叫,然後迴應所有的人......
const registerCalls =() => {
const injectormock = angular.injector(['ngMockE2E']); //lazy load not working as expected
const $httpBackend = injectormock.get('$httpBackend'); //lazy load not working as expected.
//Pass through for resources:
$httpBackend.whenGET(/.*.html/).passThrough();
$httpBackend.whenGET(/.*.json/).passThrough();
//API calls should be mocked:
const apiCalls = {};
for (var call in apiConfig) {
if ({}.hasOwnProperty.call(apiConfig, call)) {
const callConfig = apiConfig[call];
const url = angular.isDefined(callConfig.regex) ? callConfig.regex : callConfig.url();
if (callConfig.method === 'GET') {
apiCalls[call] = $httpBackend.whenGET(url);
} else if (callConfig.method === 'POST') {
apiCalls[call] = $httpBackend.whenPOST(url);
}
}
}
return apiCalls;
}
const success = function() {
const apiCalls = registerCalls();
for (var call in apiConfig) {
let response = {};
if (angular.isDefined(apiConfig[call].response)) {
response = apiConfig[call].response();
}
apiCalls[call].respond(200, response);
}
};
我怎樣才能設置了$ httpBackend,以便它可以被激活/停用而AngularJS應用程序正在運行?
非常好的答案,模式完美無缺 –
很高興爲你工作。 – estus