Je souhaite pouvoir activer et désactiver une application $ httpBackend dans mon application angularJS.
Cela signifie que je veux injecter le $ httpBackend paresseusement/à la demande. Il serait également agréable de pouvoir l'allumer et l'éteindre à nouveau. Par exemple, pour fournir des données d'entrée pour une application AngularJS prévisualisée à partir d'un système de gestion de contenu (CMS).
Le code ci-dessous ne fonctionne que si je déplace la ngMockE2E à une dépendance ordinaire, et injectent httpBackend $ à mon usine de manière standard.
Le code définit UPP $ httpBackend sur tous les appels à partir d'un fichier de configuration, et répond alors à tous ...
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);
}
};
Comment puis-je configurer le httpBackend $ afin qu'il puisse être activé/désactivé alors que l'application AngularJS est en cours d'exécution?
Très bonne réponse, le motif a fonctionné parfaitement –
Heureux que ça a marché pour vous. – estus