I wrote this little code in separate .js file for frontend backendless environment. I need to get myfile.json
whenever there is an ajax calling /somelink
.
angular.module('myApp')
.config(function($provide) {
$provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
})
.run(function($httpBackend, $http) {
$httpBackend.whenGET('/somelink').respond(function(method, url, data) {
$http({method: 'GET', url: '/somelink/myfile.json'})
.success(function(data, status, headers, config) {
return data;
})
.error(function(data, status, headers, config) {
});
});
});
However this code doesn't work and gave me error:
Error: Unexpected request: GET /somelink/myfile.json
Can someone help me fix this?
Note that I don't want to call $http directly to get .json file inside my code because that will trash the production code. The purpose of doing this is to keep this code for backendless development separately.
Thanks.
UPDATE 1:
I added:
$rootScope.$apply();
$httpBackend.flush();
Now I have another error in addition to same one previously: Uncaught Error: No pending request to flush !
UPDATE 2:
After playing around, I found a small hack. I put this in .run()
before all other $httpBackend mocks. Also this .js
file must be placed before all controllers/services/directives and after the app.js bootstrap.
var data;
$.ajax({
type: 'GET',
async: false,
url: '/somelink/myfile.json'
}).success(function(res) {
data = res;
}).error(function(data) {
});
Then this:
$httpBackend.whenGET('/somelink').respond(data);
The key is async: false
so that this makes sure the JSON is loaded into variable data
. All of these must happen before other objects triggered and call ajax events. This is a hack for frontend backendless development only. When production, of course this .js file is removed. I don't like this much is because using async: false
and direct $.ajax()
instead of $http
Following worked for me without any hack
$httpBackend.whenGET('/endpoint').respond($resource("/path/to.json").query());
Courtesy https://groups.google.com/d/msg/angular/grbwk-VehDE/UBIho6qcmLMJ
A very clean solution to this problem is to work with plain vanilla JavaScript
since $httpBackend
is not made to handle asynchronous
requests.
This method doesn't require jQuery
code.
$httpBackend.when('GET', 'http://localhost:3000/api/data').respond(getData());
function getData() {
var request = new XMLHttpRequest();
request.open('GET', '/db/myData.json', false);
request.send(null);
return [request.status, request.response, {}];
}
I got this tip from: https://stackoverflow.com/a/24287558/4742733
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With