当前位置: 动力学知识库 > 问答 > 编程问答 >

angularjs - Angular return promise from httpBackend.when()

问题描述:

How do you return a promise from httpBackend.when()? I wanted to load some canned data stored in a .json file and return that from httpBackend.whenGET(). When I try to return the promise from http.get('mydata.json') the response is returned to the failure callback of the factory.

function getAvailablePackagesComplete(response) {

return response.data;

}

function getAvailablePackagesFailed(error) { // {error = Object {data: undefined, status: 0, config: Object, statusText: ""}

$log.error(error.data.description);

return false;

}

function getAvailablePackages() {

return $http.get('/1.0/get-available-packages')

.then(getAvailablePackagesComplete)

.catch(getAvailablePackagesFailed)

}

var data = {"package": "test", "version": "1"}

$httpBackend.whenGET('/1.0/get-available-packages').respond(function(method, url, data) {

// return [200,data, {}] // this works

return $http.get('app/home/fixtures/mydata.json'); // contains {"package: "test", "version": "1"}

}); //this doesn't work

网友答案:

As it is currently, $httpBackend (from ngMockE2E) does not support promises within its .respond - See AngularJS GitHub Issue #11245. As $httpBackend should be used to avoid making real HTTP requests, but you could let some requests pass through.

From AngularJS Docs:

This implementation can be used to respond with static or dynamic responses via the when api and its shortcuts (whenGET, whenPOST, etc) and optionally pass through requests to the real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch templates from a webserver).

To work around what you're trying to do though, you could try to have getAvailablePackages() return the HTTP GET for your json file path and defining an $httpBackend.whenGET('pathTo.json').passThrough();

网友答案:

I was hitting the same issue and my use case was building a mock of my entire API in JS so that other people could work off line and develop the UI.

To achieve that I have developed a plugin called angular-mocks-async which decorates the httpBackend and adds the .whenAsync( ) APi to it. Than you can easily mock responses and return promises like so:

var app = ng.module( 'mockApp', [
    'ngMockE2E',
    'ngMockE2EAsync'
]);

app.run( [ '$httpBackend', '$q', function( $httpBackend, $q ) {

    $httpBackend.whenAsync(
        'GET',
        new RegExp( 'http://api.example.com/user/.+$' )
    ).respond( function( method, url, data, config ) {

        var re = /.*\/user\/(\w+)/;
        var userId = parseInt(url.replace(re, '$1'), 10);

        var response = $q.defer();

        setTimeout( function() {

            var data = {
                userId: userId
            };
            response.resolve( [ 200, "mock response", data ] );

        }, 1000 );

        return response.promise;

    });

}]);
分享给朋友:
您可能感兴趣的文章:
随机阅读: