angular-translate with angular-mocks results in blank page - angularjs

I'm trying to mock a request/response using ngMock and get this error: Unexpected request: GET /locales/en_us.json. After digging around I found this post on how to get around the error. Adding $translateProvider.preferredLanguage('en_us') fixed the error but the templates aren't rendering i.e., I just see a blank page. In the run method I have the following:
$httpBackend.whenGET(env.baseUri + '/1.0/test-data').respond(function(method, url, data){
return [200, [
{
"id": 1,
"name": "test name",7,
"version": "1.0"
}
]]
In the config method:
$translateProvider.preferredLanguage('en_us');
EDIT I fixed this error by adding a passThrough for "locales":
myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
myAppDev.run(function($httpBackend) {
phones = [{name: 'phone1'}, {name: 'phone2'}];
// adds a new phone to the phones array
$httpBackend.whenPOST('/phones').respond(function(method, url, data) {
var phone = angular.fromJson(data);
phones.push(phone);
return [200, phone, {}];
});
$httpBackend.whenGET(/^\/locales\//).passThrough();
});

The fix was to add $httpBackend.whenGET(/^/locales//).passThrough(); see above.

Related

Send data by post from AngularJs to Django

I want to send data from AngularJS to the back end (Django) via Http request.
I tried many ways but I keep not getting the sent data when receiving the request in django.
Before I paste my code, I just have changed the configurations in AngularJS in my project as the following
var myApp = angular.module('myApp',[]).config(['$httpProvider', '$interpolateProvider', function ($httpProvider, $interpolateProvider) {
$interpolateProvider.startSymbol('{/');
$interpolateProvider.endSymbol('/}');
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';}]);
The urls:
urlpatterns = [
url(r'^save_comment/', views.save_comment, name='save_comment'),]
Sending Https POST in Angular:
$scope.submit_comment = function () {
$http({
method: "POST",
url: 'save_comment',
data: $.param({
'fish_id' : "1"
})
}).success(function (response) {
console.log(response.result);
}).error(function () {
console.log("failed")
}); }
Receiving the request in the Views
def save_comment(request):
data = request.POST.get('fish_id')
return JsonResponse({'result': data}, content_type="application/json", safe=False)
But I didn't get any result. the console gave me this error:
POST http://127.0.0.1:8000/brain_browser/save_comment 500 (Internal
Server Error)
So what should I do to send Post data from Angular to Django?
Thank in a dvance.
Not an answer but you can debug yourself. Add this to settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
Your url: 'save_comment' seems to be missing a slash at the beginning, since your url expects http://127.0.0.1:8000/save_comment/ but because of the missing slash you are sending http://127.0.0.1:8000/brain_browser/save_comment.
So change the url in your Javascript to url: '/save_comment/'
Edit: #bobleujr's answer could also fix the problem if csrf tokens are the problem. In my personal Angular/Django project I simply put this at the very top of my javascript:
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}]);
2nd Edit: This should be the solution
In your views, do this instead of data = request.POST.get('fish_id'):
body_unicode = request.body.decode('utf-8')
data = json.loads(body_unicode)
# Work with "data" from now on, i.e:
print(data["fish_id"])
This is because request.body (Your parameters) is a byte string, and json.loads does not accept byte strings.
Also make sure you have json imported in your views at the very top like so:
import json

Bug - AngularJS Service with GET JSON file

I am working on a simple sample AngularJS application that reads data from an external JSON data file. I have tried everything, and I cannot find why the application does not work. Any input would be most appreciated.
'filmCtrl' Control:
angular
.module('mediaApp')
.controller('filmCtrl', function(filmList) {
var vm = this;
vm.films = filmList.retrieveFilms();
});
'filmList' Service:
angular
.module('mediaApp')
.service('filmList', function($http) {
var vm = this;
vm.retrieveFilms = function() {
return $http
.get('films.json')
.then(function(response) {
return response.films;
});
};
return vm;
});
JSON:
{
"films":[
{
"title": "Reservoir Dogs",
"director": "Quentin Tarantino",
"year": "1992"
},
{
"title": "2001: A Space Odyssey",
"director": "Stanley Kubrick",
"year": "1967"
},
{
"title": "Memento",
"director": "Christopher Nolan",
"year": "2000"
},
{
"title": "Enter the Dragon",
"director": "Robert Clouse",
"year": "1973"
},
[etc]...
]
}
All of these files are saved in the same folder, and have been included in my HTML file. The JSON has been validated. Where have I gone wrong?
As per my comments you can create service like this -
mediaApp.service('filmList', ['$http',
function($http) {
var vm = this;
vm.retrieveFilms = function() {
return $http.get('data.json');
};
return vm;
}]);
In controller you can consume this service like -
mediaApp.controller('filmCtrl', function(filmList) {
var vm = this;
filmList.retrieveFilms().then(function(response) {
vm.films =response.data.films;
});
});
Working Plnkr - http://plnkr.co/edit/6RVlvdh8oG5WaiEHaPdM?p=preview
It will work in FF but for some browsers it will throw CORS error so better run it on a server.
In a then(response) the response object has these properties:
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
So this should be
return $http
.get('films.json')
.then(function(response) {
return response.data.films;
});
instead of
return $http
.get('films.json')
.then(function(response) {
return response.films;
});
See the official doc for more info.
If you're not running a webserver of any kind and just testing with file://films.json, then you're probably running into same-origin policy issues. See:
http://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy
Some error message could be useful.

Cordova FileTransfer: upload image to AWS s3

Am using ng-cordova file-Transfer plugin to upload images to my AWS s3 bucket.
but i run into two problems first it didn't work, second i have no idea how to debug the problem while the App running on the emulater.
here is my code:
.controller('newItemCtrl', function($scope, $http, API_URL, me, $cordovaFileTransfer) {
var s3URI = encodeURI("https://mybucketname.s3.amazonaws.com/"),
policyBase64 = "MY_BASE64_ENCODED_POLICY_FILE",
signature = "MY_BASE64_ENCODED_SIGNATURE",
awsKey = 'my AWSAccessKeyId',
acl = "public-read";
var options = {
fileKey: "avatar",
fileName: "image.png",
chunkedMode: false,
mimeType: "image/png"
// params = {
// "key": fileName,
// "AWSAccessKeyId": awsKey,
// "acl": acl,
// "policy": policyBase64,
// "signature": signature,
// "Content-Type": "image/png"
// }
};
var imageURI = '../img/ionic.png';
$scope.upload = function($cordovaFileTransfer) {
$cordovaFileTransfer.upload(s3URI, imageURI, options)
.then(function(result) {
console.log("SUCCESS: " + JSON.stringify(result.response));
}, function(err) {
console.log("ERROR: " + JSON.stringify(err));
}, function(progress) {
// constant progress updates
});
}
})
I also left the params code to ask another question it's commented, but before i run my app and it gives me an error with the params but my question why i got the error even before invoke the template assosiated with that controller
I had a similar problem, to debug I used the live server logs to check and see if the file upload hit the server at all, some errors I noticed:
my server was expecting a different file key
the Access-Control-Allow-Origin header wasnt being sent properly in the server's response
Then, I also installed the cordova native notifications plugin (link here) and sprinkled alerts throughout the file transfer callbacks to see where things were getting stuck
Anyway probably not the best way to debug, but it worked.
Hope that helps.
...one more thing the params part of "options" seems to work best when applied in this format:
var options = {
fileKey: "avatar",
fileName: "image.jpg",
/*params: {
"value1":"value1",
"value2": "value2"
}*/
};
var params = new Object();
params.value1 = "value1";
params.value2 = "value2";
options.params = params;
from the cordova docs "params: A set of optional key/value pairs to pass in the HTTP request. (Object)" so passing in a dictionary may be subtly different, I'm not sure, all I know is that it worked once I made that change.
To debug on emulator I use this from my app directory: ionic emulate ios -lc
That shows me errors or logs into the console.

Module factory is not returning data

I am trying to read JSON reply from server. You can find my code here.
https://github.com/ameyjah/feeder
In firefox firebug, I can see that server has returned JSON reply but when I store that into $scope.variable, I am not able to access that information.
Module code
var res
angular.module('myApp.services', ['ngResource'])
.factory('feedFetcher', ['$resource',
function($resource) {
var actions = {
'sites': {method:'GET', params: { action:"sites"} ,isArray:false},
'feeds': {method:'GET', params: { action:"sites"} ,isArray:false}
}
res = $resource('/api/:action', {}, actions);
return res
}
]);
Controller code
$scope.sites = feedFetcher.sites().sites;
console.log($scope.sites);
Reply seen in firebug:
{
"sites": [
{
"id": 0,
"title": "google"
},
{
"id": 1,
"title": "yahoo"
}
]
}
I think I have messed up the way I should define my factory but I am not able to identify. Any help would be helpful.
When you call sites() it returns an empty object and initiates an AJAX request, which will populate the "sites" property on that object. I think you should use it like this:
$scope.results = feedFetcher.sites();
console.log($scope.results.sites); // will be undefined as AJAX not complete
Then in your html you can use the results and they will be filled in when AJAX completes, or watch for it:
$scope.$watch('results.sites', function() {
// this will be called twice, once initially
// and again whenever it is changed, aka when AJAX completes
console.log($scope.results.sites);
};

angular js jsonp example dosn't works

im having trouble using the angular js jsonp function, i cant make this plunk to work:
http://plunker.co/edit/xQVBchTYOro1CB979021
can anyone help me?
With the JSONP "hack" you must make sure that the server's response contains callback's invocation. To make your example work you should change the prov.json file so it looks like follows:
angular.callbacks._0({
"id": "40796308305",
"about": "The Coca-Cola Facebook Page is a collection of your stories showing how people from around the world have helped make Coke into what it is today.",
...
})
There are many sources on JSONP, ex.: What is JSONP all about?
using a get instead of jsonp, you get the details of cokacola...
async: function(page) {
var url = 'prov.json';
var promise = $http.get(url).error(function (response, status) {
alert("fai");
}).success(function (response, status) {
alert(response.about);
}).then(function (response, status) {
return response.data;
});
return promise;
}};

Resources