【发布时间】:2017-04-11 01:34:59
【问题描述】:
我希望能够在我的 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 应用程序运行时激活/停用它?
【问题讨论】:
标签: javascript angularjs httpbackend