How do I write this as an AngularJS $http.get? - angularjs

I was wondering, how could this be written in angularJS?
requests: {
fetchUsers: function() {
return {
url: 'https://www.example.com/api/v2/users',
type: 'GET',
username: 'myemail#email.com/token',
password: 'myAPItoken'
};
}
}

This is just an example:
Your controller:
var userCtrl = angular.module('UserCtrl',[]);
userCtrl.controller('UserController',function($scope,Users){
var getUsers = Users.fetchAll();
getUsers.then(function(response){
$scope.users = response;
});
});
Your service:
var userSrvc = angular.module('UserSrvc',[]);
userSrvc.factory("Users",function($http){
return{
fetchAll: function(){
var request = $http({method:'GET', url:'https://www.example.com/api/v2/users'});
return request;
}
}
});

Related

PUT request to Amazon S3 bucket using presigned url returns 403

I'm getting the presigned url from a Node.js server using aws-sdk. Here is the server code, which always returns a 200 code and a the url:
getSignedUrl: function(req, res, next){
aws.config.update({ accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY });
var s3 = new aws.S3();
var s3_params = {
Bucket: S3_BUCKET,
Key: req.query.file_name,
ContentType: req.query.file_type,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3_params, function(err, data){
if (err) {
return next(err);
}
else {
var return_data = {
signed_request: data,
url: 'https://'+S3_BUCKET+'.s3.amazonaws.com/'+req.query.file_name
};
res.json(return_data);
}
});
}
My client-side is Angular. I've uloaded a file using a File Reader service:
.factory('fileReaderFactory', ['$q', '$log', function($q, $log){
....
var getReader = function(deferred, scope) {
var reader = new FileReader();
....
return reader;
};
var readAsDataURL = function (file, scope) {
var deferred = $q.defer();
var reader = getReader(deferred, scope);
scope.$broadcast("fileData", {
name: file.name,
type: file.type
});
reader.readAsDataURL(file);
return deferred.promise;
};
return {
readAsDataUrl: readAsDataURL
};
}]);
My controller:
.controller('UploadCtrl', ['apiFactory','fileReaderFactory','$scope', function(apiFactory, fileReaderFactory, $scope){
$scope.data = {};
$scope.fileData = {};
...
$scope.readFile = function() {
fileReaderFactory.readAsDataUrl($scope.file, $scope)
.then(function(result){
$scope.imgSrc = result;
imgUploaded = true;
});
};
$scope.upload = function(){
apiFactory.getSignedUrl($scope.fileData)
.then(function(result){
return apiFactory.uploadS3(result, $scope.fileData, $scope.imgSrc);
})
.then(function(result){
}, function(error){
console.log(error);
})
};
....
}]);
And finally the snippets of code from the apiFactory:
apiFactory.getSignedUrl = function(data){
return $http({
method: 'GET',
url: API_URL + '/sign_s3',
params : {
"file_name": data.name,
"file_type": data.type,
}
});
};
apiFactory.uploadS3 = function(result, data, file){
return $http({
method: 'PUT',
url: result.data.signed_request,
data: file,
headers: {
"x-amz-acl": "public-read"
}
});
}
I always get a 403: Forbidden back from Amazon when I try to upload the file using the signed url, however.

why it fails when I declare a function to invoke in controller

It will fail to bind data from http response if you uncomment "//" line,why? It should be the same, right?
var m = angular.module('users', []);
m.controller('UserList', function($scope) {
// $scope.getdata = function() {
var u = "http://wisebe.duapp.com/admin?queryusers";
var userList = this;
var body = {
activityid: "10",
checkin: $('#checkin').val()
};
$.ajax({
url: u,
type: "post",
async: false,
data: body,
success: function(data) {
userList.users = data;
}
});
// };
// $scope.getdata();
$('#checkin').change(function() {
// $scope.$apply();
});
});

How do I delete a post using this with angularJS and express?

I have this code in my post.serv.js and in my controller I want to execute the function delete.
"use strict";
app.factory('JnttPost', function ($resource) {
var PostResource = $resource('/api/post/:_id', {
_id: "#id"
}, {
update: {
method: 'PUT',
isArray: false
}
}, {
delete: {
method: 'DELETE',
isArray: false
}
});
return PostResource;
});
I already know how to get and update a post, for example in my createpost.serv.js
"use stric";
app.factory('JnttCreatePost', function ($http, $q, JnttPost) {
return {
createPost: function (newPostData) {
var newPost = new JnttPost(newPostData);
var dfd = $q.defer();
newPost.$save().then(function () {
dfd.resolve();
}, function (response) {
dfd.reject(response.data.reason);
});
return dfd.promise;
}
};
});
and in my newpost.ctrl.js
"use strict";
app.controller('CtrlNewPost',
function ($scope, $location, JnttIdentity, JnttNotifier, JnttCreatePost) {
var email = ...;
$scope.newPost = function () {
var newPostData = {...};
JnttCreatePost.createPost(newPostData).then(function () {
JnttNotifier.notify('success', 'The post has been created');
$location.path('/');
}, function (reason) {
JnttNotifier.notify('error', reason);
});
};
});
I can't realize how to perform the delete request, I can do with a $http
In my new controller for do deletePost() function I have this:
$scope.deletePost = function () {
var pwd = JnttIdentity.currentUser.hashed_pwd;
var postidd = {
password: pwd,
id: $scope.post._id
};
var config = {
method: "DELETE",
url: '/api/post/',
data: postidd,
headers: {
"Content-Type": "application/json;charset=utf-8"
}
};
$http(config);
$location.path('/');
};
This actually already do this stuff but I want to do this without the $http like the create request, How I can do this? How do I can edit this code below for do the request?
createPost: function (newPostData) {
var newPost = new JnttPost(newPostData);
var dfd = $q.defer();
newPost.$save().then(function () {
dfd.resolve();
}, function (response) {
dfd.reject(response.data.reason);
});
return dfd.promise;
}
In my routes.js in express I have this route:
app.delete('/api/post/', posts.deletePost);
You can either call delete on the $resource class you create (JnttPost) or call $delete on a post that's returned from the $resource class.
The $resource class already has get/save/query/remove/delete functions included so you don't need to add the delete (save is create/POST, so you need to include update with PUT).
Here's a sample of using your $resource class to call delete:
angular.module('test', ['ngResource'])
.factory('JnttPost', function ($resource) {
var PostResource = $resource('/api/post/:_id', {
_id: "#id"
}, {
update: {
method: 'PUT',
isArray: false
}
});
return PostResource;
})
.run(function(JnttPost){
JnttPost.delete({id: 123123123});
});

Storing tokens with OAuth 2.0 in Angular

I have an app which displays Google Calendar data, but it requires an initial login. I know it's possible to store tokens using OAuth 2.0, but I'm not sure how to go about doing it. Here is my code below. I'd like for the webpage to display the a calendar using JSON data from a google calendar without login.
Controller
angular.module('demo', ["googleApi"])
.config(function(googleLoginProvider) {
googleLoginProvider.configure({
clientId: '239511214798.apps.googleusercontent.com',
scopes: ["https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/plus.login"]
});
})
.controller('DemoCtrl', ['$scope', 'googleLogin', 'googleCalendar', 'googlePlus', function ($scope, googleLogin, googleCalendar, googlePlus) {
$scope.login = function () {
googleLogin.login();
};
$scope.$on("googlePlus:loaded", function() {
googlePlus.getCurrentUser().then(function(user) {
$scope.currentUser = user;
});
})
$scope.currentUser = googleLogin.currentUser;
$scope.loadEvents = function() {
this.calendarItems = googleCalendar.listEvents({calendarId: this.selectedCalendar.id});
}
$scope.loadCalendars = function() {
$scope.calendars = googleCalendar.listCalendars();
}
}]);
googleAPi
angular.module('googleApi', [])
.value('version', '0.1')
.service("googleApiBuilder", function($q) {
this.loadClientCallbacks = [];
this.build = function(requestBuilder, responseTransformer) {
return function(args) {
var deferred = $q.defer();
var response;
request = requestBuilder(args);
request.execute(function(resp, raw) {
if(resp.error) {
deferred.reject(resp.error);
} else {
response = responseTransformer ? responseTransformer(resp) : resp;
deferred.resolve(response);
}
});
return deferred.promise;
}
};
this.afterClientLoaded = function(callback) {
this.loadClientCallbacks.push(callback);
};
this.runClientLoadedCallbacks = function() {
for(var i=0; i < this.loadClientCallbacks.length; i++) {
this.loadClientCallbacks[i]();
}
};
})
.provider('googleLogin', function() {
this.configure = function(conf) {
this.config = conf;
};
this.$get = function ($q, googleApiBuilder, $rootScope) {
var config = this.config;
var deferred = $q.defer();
return {
login: function () {
gapi.auth.authorize({ client_id: config.clientId, scope: config.scopes, immediate: false}, this.handleAuthResult);
return deferred.promise;
},
handleClientLoad: function () {
gapi.auth.init(function () { });
window.setTimeout(checkAuth, 1);
},
checkAuth: function() {
gapi.auth.authorize({ client_id: config.clientId, scope: config.scopes, immediate: true }, this.handleAuthResult );
},
handleAuthResult: function(authResult) {
if (authResult && !authResult.error) {
var data = {};
$rootScope.$broadcast("google:authenticated", authResult);
googleApiBuilder.runClientLoadedCallbacks();
deferred.resolve(data);
} else {
deferred.reject(authResult.error);
}
},
}
};
})
.service("googleCalendar", function(googleApiBuilder, $rootScope) {
var self = this;
var itemExtractor = function(resp) { return resp.items; };
googleApiBuilder.afterClientLoaded(function() {
gapi.client.load('calendar', 'v3', function() {
self.listEvents = googleApiBuilder.build(gapi.client.calendar.events.list, itemExtractor);
self.listCalendars = googleApiBuilder.build(gapi.client.calendar.calendarList.list, itemExtractor);
self.createEvent = googleApiBuilder.build(gapi.client.calendar.events.insert);
$rootScope.$broadcast("googleCalendar:loaded")
});
});
})
.service("googlePlus", function(googleApiBuilder, $rootScope) {
var self = this;
var itemExtractor = function(resp) { return resp.items; };
googleApiBuilder.afterClientLoaded(function() {
gapi.client.load('plus', 'v1', function() {
self.getPeople = googleApiBuilder.build(gapi.client.plus.people.get);
self.getCurrentUser = function() {
return self.getPeople({userId: "me"});
}
$rootScope.$broadcast("googlePlus:loaded")
});
});
})
What you will want to do is after the result comes back you will want to save it off to localStorage or a cookie and then use that in the future if it exists.
Essentially you will need to update your handleAuthResult to store the result from the Google API:
handleAuthResult: function (authResult) {
if (authResult && !authResult.error) {
var data = {};
$rootScope.$broadcast("google:authenticated", authResult);
googleApiBuilder.runClientLoadedCallbacks();
// here you will store the auth_token
window.localStorage.setItem('auth_token', authResult.token /*I don't know what this response looks like, but it should be similar to this*/ );
deferred.resolve(data);
} else {
deferred.reject(authResult.error);
}
},
Live Demo

angular .then() is not recognized

I try to use .then() in my angular controller
angular.module('n2goApp')
.controller('MainCtrl', function($scope, Products) {
Products.get(). then( function ( response ) {
$scope.data = response;
console.log(response);
$scope.totalPages = response.TotalPages;
$scope.totalItems = response.total;
$scope.products = response.data;
$scope.currentPage = response.current_page;
$scope.maxSize = 5;
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
});
});
but drops me an error
Error: Products.get(...).then is not a function
Service
angular.module('n2goApp')
.service('N2goservice', function N2goservice() {
// AngularJS will instantiate a singleton by calling "new" on this function
}).factory('Products', ['$resource', function($resource) {
var url = 'http://domain.com/api/products';
return $resource( url + '/:prodID',
{ bookId: '#prodID' }, {
loan: {
method: 'PUT',
params: { prodId: '#prodID' },
isArray: false
},
get:{
method: 'GET',
params: {
prodId: '#prodID',
page:'#page'
},
isArray: false
}
/* , method3: { ... } */
} );
}]);
What I'm doing wrong?
You have to get the $promise from the resource. Like this:
Products.get().$promise.then(..)
Or you can use the other syntax with callback
Products.get({},function(response) {
});

Resources