I am new to Angular, and trying to figure out how the best way to do this is. In my Django view, I authenticate a user, storing that user in request.user. Is there a way to retrieve that request.user in an Angular module. Can I retrieve it through Angular's $http service ? Looked around, but couldn't find a solution to this...yet, and thought I would try good ole Stack Overflow.
function bindPusher() {
var defer = $q.defer();
var channelName = 'private-account-' + Session.account.id;
var channel = $pusher.client.subscribe(channelName);
channel.bind('pusher:subscription_succeeded', function (data) {
$log.debug('Pusher subscribed: ' + channel.name);
PushListener.bindAndListen(channel);
defer.resolve(data);
});
channel.bind('pusher:subscription_error', function (status) {
if (status === 403) {
var msg = 'Pusher channel not authorized.';
$log.warn(msg);
defer.reject(msg);
}
});
return defer.promise;
}
Angular runs in the browser, Django runs on the server. Use a JSON string to send the data of Django's request.user to the browser, where Angular can unwrap that JSON string into a Javascript object.
So, you are correct, $http.get('/path/my-user.json') could read the request.user's data.
$http.get('/path/my-user.json').then(function (response) {
$scope.user = response.data.user;
}, function (reject) {
// error
});
In your Django view, you would send the data as a JSON encoded string.
def my_view(request):
data = {'username': request.user.username,
'is_staff': request.user.is_staff}
return JsonResponse(data)
But, these are Django and Angular, so there are many things to automate much of this, once you understand the basics. Namely Django Restframework and the Angular Resource Service.
Related
So I'm making a post request to my Express search router where I'm using the node-fetch module to call a remote api:
var fetch = require('node-fetch');
router.route('/search')
//Performs Job Search
.post(function(req, res){
var area = req.body.area;
fetch('https://api.indeed.com/ads/apisearch?publisher=*********&l=' + area)
.then(function(res) {
return res.json();
}).then(function(json) {
console.log(json);
});
})
I'm using angular 1 on the client side to call the router and parse the returned json:
$scope.search = function(){
$http.post('/api/search', $scope.newSearch).success(function(data){
if(data.state == 'success'){
//perform JSON parsing here
}
else{
$scope.error_message = data.message;
}
});
}
I'm just starting out with the MEAN stack and only have a vague idea of how promises work. So my issue is that my angular search function is not getting the JSON string I want to return from my remote API call. But rather the data parameter is getting set to my page html. Eventually the breakpoints I've set in the .then() clauses are hit and my json is returned. So my question is how can I use Anguular to get the JSON values when they are finally returned????
Can you try something like this?
router.route('/search')
//Performs Job Search
.post(function(req, res){
var area = req.body.area;
fetch('https://api.indeed.com/ads/apisearch?publisher=*********&l=' + area)
.then(function(result) {
res.json(result);
//or possibly res.send(result), depending on what indeed responds with
})
})
Turns out I had forgotten that I had middleware in place where if the user was not authenticated when performing the search they were redirected to the login page. So I was getting a bunch of html returned for this login page, rather then my json. What still confuses me is why my breakpoints in search function were ever hit if I was being redirected before ever reaching this function.
I am trying multiple ways to access my users in a local json file in able to later compare them to the users input. and if there is a match, access is allowed, but my main problem now is just getting to those users.
My code so far:
entire code
json file
What am i doing wrong? i am such a newbie in programming. I have been trying different things and nothing works.
Thanks so much for help
Can you access the file through the browser (via your url localhost:8080/resources/data/users.json)?
If you can't, you will not be able to get access through the $resource or $http.
If you can, any method should work:
1) Via $resource
$scope.users = [];
var UsersResource = $resource('/resources/data/users.json');
where we can get response by callback
UsersResource.get({}, function(response) {
$scope.users = response;
});
or by $promise
UsersResource.get().$promise.then(function(response) {
$scope.users = response;
});
2) Via $http.get
$scope.users = [];
$http.get('/resources/data/users.json').then(function(response) {
$scope.users = response;
});
In your sample, your are trying to get array of users by returning $resource, but $resource returns a object with methods. Each method has callbacks (success, error) or return $promise object.
There is no need to use $resource if you are just going to fetch a json file. Use $http instead:
this.getUsers = function(){
return $http.get('path/to/file.json');
};
And usage:
dataService.getUsers().then(function(resp){
//Do something with the data
$scope.users = resp;
})
$resource is meant to be used when communicating with RESTful apis. What your getUsers() is doing is actually returning a resource-object, upon which you can then call get(). But I recommend using $http in this case.
If you want to use $resouce then you need to create two functions in your controller/factory where "templatesSuccess" return data of request.
getAllTemplates: function(query) {
return $resource(CONST.CONFIG.BASE_URL + 'receiver/get-templates').get(query, obj.templatesSuccess).$promise;
},
templatesSuccess: function(response) {
obj.allTemplates = response;
},
I have an Ionic project with a WCF RESTful service, I want to be able to Insert and Update data. I can already view data with GET method but can't find anything on the internet for PUT and POST. How would I be able to accomplish this?
GET Method
$scope.selectedDist= function() {
$http.get("http://192.168.1.113/Service1.svc/GetAllComp")
.success(function(data) {
var obj = data;
var ar = [];
angular.forEach(obj, function(index, element) {
angular.forEach(index, function(indexN, elementN) {
ar.push({CompID: indexN.CompID, CompName: indexN.CompName});
$scope.districts = ar;
});
});
})
.error(function(data) {
console.log("failure");})
};
Post methods I tried
#1
$scope.insertdata = function() {
var ar = [{'M1':$scope.M1, 'M2':$scope.M2,'M3':$scope.M3,'M4':$scope.M4,'M5':$scope.M5,'M6':$scope.M6,'M7':$scope.M7,'M8':$scope.M8,'M9':$scope.M9,'M10':$scope.M10,}]
$http.post("http://192.168.1.113/Service1.svc/GetAllComp", ar)
.success(function(data)
{
console.log("data inserted successfully")
})
.error(function(data)
{
console.log("Error")
})
#2
$scope.insertdata = function() {
var ar = [{'M1':$scope.M1, 'M2':$scope.M2,'M3':$scope.M3,'M4':$scope.M4,'M5':$scope.M5,'M6':$scope.M6,'M7':$scope.M7,'M8':$scope.M8,'M9':$scope.M9,'M10':$scope.M10,}]
$http ({
url : "localhost:15021/Service1.svc/TruckDetails" ,
Method : "POST" ,
headers : {
'Content-Type' : 'Application / json; charset = utf-8'
},
Data : ar
})
Also Would I need to make a POST or PUT method on my Service as well or can I use the GET methods?
You can use a get method, in combination with a querystring to post and put data but that is not what it was designed for and should be avoided for several reasons such as security.
That being said, it is not that difficult to use post and put in angular and in the following , rather naive service , you can see all that is required to do is passing your data in the service function you're invoking.
.service('MyService', function($http) {
this.postMethod = function(data) {
return $http.post('http://my.url', data);
};
this.putMethod = function(id, data) {
return $http.put('http://my.url/' + id, data);
};
}
So that in your controller you can inject and invoke the service methods with the $scope data that needs to be stored.
After taking a look at your attempts you seem to be using the same url for both get and post: "http://192.168.1.113/Service1.svc/GetAllComp" which actually leads me to believe you haven't thought about implementing these methods on your server. Can you confirm this?
Apart from that, it is always usefull to look at statuscodes when trying to send requests because they provide a great deal of information about the nature of the error that occurs. You can investigate that in either your console or an external program such as Fiddler.
P.S.
Deprecation Notice The $http legacy promise methods success and error
have been deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
My AngularJS application is interacting with ASP.NET Web API to full fill the request which is working fine. it has an use case that allows user to download user specific secure PDF document. I have implemented this functionality as below
AngularJS:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
$scope.DownloadHandler = function (id, downloadURL) {
FileStreamManager.getPdf(id, downloadURL)
.then(function (result) {
// success
window.open(downloadURL + id, '_self', '');
},
function (result) {
$scope.errors = result.data;
});
};
Note : downloadURL is the Controller call like \ImageRepo\Get
Web Api Controller I have this implementation:
HttpResponseMessage response = new HttpResponseMessage();
// DB call to to build the URL
string fileName = "myLocation\Image\doc.pdf";
if (!fileProvider.Exists(fileName))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
FileStream fileStream = fileProvider.Open(fileName);
response.Content = new StreamContent(fileStream);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentLength = fileProvider.GetLength(fileName);
return response;
Which is working fine. Due to the security issue, i was asked to implement this by using HttpHanlder which is pretty new to me. I have some question on the same.
Should my AngularJS ng-click calls to my .ashx handler directly instead of a Controller URL? Or Should this call route through Controller? How?
I have DB calls to build the image URL and update some the status. Can this be done in Handler itself?
How would i make sure my documents are secured while downloading?
Please help.
I have a SPA with a list of Clients displayed on the landing page. Each client has an edit button, which if clicked should take me to an Edit view for that selected Client.
I'm not sure how to go about this- all the routes I've seen so far will just take my client id in the $routeParams, and then most examples will then pull the Client from a factory by that Id.
But I already HAVE my Client... seems a waste to hit my web api site again when I already have it. Is it possible to route to the new view and maintain the selected Client in the $scope?
Edit:
This is what I did- I don't know if it's better or worse than Clarks response... I just made the following angular service:
app.service('clientService', function () {
var client = null;
this.getClient = function () {
return client;
};
this.setClient = function (selectedClient) {
client = selectedClient;
};
});
And then for any controller that needs that data:
$scope.client = clientService.getClient();
This seemed to work fine... but would love to hear how this is good or bad.
Depends on what level of caching you want.
You could depend on browser caching, in which case proper HTTP headers will suffice.
You could depend on cache provided by $http in angular, in which case making sure the parameters you send up are the same would be sufficient.
You could also create your own model caching along the lines of :
module.factory('ClientModel', function($http, $cacheFactory, $q){
var cache = $cacheFactory('ClientModel');
return {
get : function(id){
var data = cache.get(id);
if(data){
//Using $q.when to keep the method asynchronous even if data is coming from cache
return $q.when(data);
} else {
//Your service logic here:
var promise = $http.get('/foo/bar', params).then(function(response){
//Your model logic here
var data = response;
cache.put(id, data);
return response;
}, function(response){
cache.remove(id);
return response;
});
//Store the promise so multiple concurrent calls will only make 1 http request
cache.put(id, promise);
return promise;
}
},
clear : function(id){
if(angular.isDefined(id)){
cache.remove(id);
} else {
cache.removeAll();
}
}
}
});
module.controller('ControllerA', function(ClientModel){
ClientModel.get(1).then(function(){
//Do what you want here
});
});
module.controller('ControllerB', function(ClientModel){
ClientModel.get(1).then(function(){
//Do what you want here
});
});
Which would mean each time you request a client object with the same 'id', you would get the same object back.