AngularJS - Using ngMockE2E $httpBackend how can I delay a specific response?

坚强是说给别人听的谎言 提交于 2019-12-24 11:23:08

问题


I'd like to delay the response to the following whenGET:

$httpBackend.whenGET(/^foobar/).respond(function () {
  return [200,{}];
});

However it seems impossible using $timeout to do this synchronously, so I'm not sure how to approach this?


回答1:


If you want to delay only a specific response, than you may delay assignment of the reponse to scope property.

If you wrap your call into your custom service method, than you may wrap the response into the promise and resolve it when needed:

JS:

angular.module('app').service('myService', function($q, $timeout){

 this.getData = function() {
    var delay = 300,
        origPromise = $http.get('someUrl'),
        deferred = $q.defer();
    $timeout(function() {
       deferred.resolve(origPromise);
    }, delay);

    return defered.promise;
 };

});

[EDIT]:

To set the delay to all requests, you may apply this solution to the response interceptor



来源:https://stackoverflow.com/questions/26083822/angularjs-using-ngmocke2e-httpbackend-how-can-i-delay-a-specific-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!