Using Parse.com REST-API with AngularJS - javascript

I would like to use Parse with AngularJS. I'm a new one in both...
I'm trying to create a new user but i receive the error "bad request".
Here is my controller (linked to two input html tags):
var myAppControllers = angular.module('myApp.controllers', []);
myAppControllers.controller('SignUpCtrl', ['$scope', '$http',
function($scope, $http) {
$scope.results = []
$scope.signUp = function() {
$http({method : 'POST',
url : 'https://api.parse.com/1/users',
headers: { 'X-Parse-Application-Id':'xxx', 'X-Parse-REST-API-Key':'xxx'},
params: {
where: {
username: $scope.username,
password: $scope.password
}
}} )
.success(function(data, status) {
$scope.results = data;
})
.error(function(data, status) {
alert("Error");
})
}
}]);

Related

How to call php file via factory/service method using Angular.js

I need to call php file using service/Factory method using Angular.js. Here instead of calling $http repeatedly in each file to call diferent php file for different purpose, I need to make it common. I am explaining one example below.
logincontroller.js:
var loginAdmin=angular.module('Takeme');
loginAdmin.controller('loginController',function($scope,$http,$location,$window,inputField){
$http({
method: 'POST',
url: "php/Login/verify.php",
data: userData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
},function errorCallback(response) {
});
}
I have one common route.js file which is common for all controller and given below.
route.js:
var Admin=angular.module('Takeme',['ui.router', '720kb.datepicker','ngMessages','ngCapsLock','ui.bootstrap','ngFileUpload','angularUtils.directives.dirPagination']);
Admin.run(function($rootScope, $state) {
$rootScope.$state = $state;
});
Admin.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/',{
url: '/',
templateUrl: 'view/login.html',
controller: 'loginController'
})
})
Admin.factory('inputField',function($timeout,$window){
return{
borderColor:function(id){
$timeout(function() {
var element = $window.document.getElementById(id);
if(element){
element.focus();
element.style.borderColor = "red";
}
});
},
clearBorderColor:function(id){
$timeout(function() {
var element = $window.document.getElementById(id);
if(element){
element.style.borderColor = "#cccccc";
}
});
}
};
});
Here I need to that $http service to call the php file common for which in every controller I will call that $http repeatedly. I need to pass only the parameters for $http service and return the response.
create a factory/service
angular.module('myApp').factory('DataService', DataService);
DataService.$inject = ['$http', '$q'];
function DataService($http, $q) {
return {
getData: getData,
}
function getData(userData) {
var deferred = $q.defer();
$http({
method: 'POST',
url: "php/Login/verify.php",
data: userData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
deferred.resolve(response.data);
},
function(error) {
deferred.reject(error.data);
});
return deferred.promise;
};
}
then use this factory whenever you need in a controller
angular.module('myApp')
.controller('MyController', ['$scope', 'DataService',
function($scope, DataService ) {
$scope.getMyData = function() {
var data = {};
DataService.getData(data)
.then(function(response) {
}, function(error) {
});
};
}
]);

Access data from one controller to another controller- AngularJS

addressbookController :
$http({
method: 'GET',
url: '/api/getnewgroup'
})
.then(function (response) {
$scope.draft.groups = response.data;
$scope.groups = response.data; // updated
}, function (response) {
console.log(response);
});
In this above controller, i am getting json response in $scope.draft.groups, I have this draft object in another controller called profsmsController.
profsmsController :
$scope.draft = {
draftType: '',
scheduledTime: '',
senderdata: '',
draftData: {
contacts: ''
},
groups: {
select: false
},
senderName: '',
message: '',
draftName: '',
createdOn: '',
updatedOn: ''
};
How to access $scope object ?
My Controller:
angular
.module('sampleApp.controllers', [])
//addressbook page controller
.controller('addressbookCtrl', function ($http, $scope, $rootScope, $location,
$state, toastr, $timeout, $window, sharedService) {
// Groups
// get group
$http({
method: 'GET',
url: '/api/getnewgroup'
})
sharedService.getDraftPromise().then(function (response) {
$scope.groups = response.data;
$scope.draft.groups = response.data;
}, function (response) {
console.log('error');
});
})
.controller('profsmsCtrl', function ($http, $scope, $rootScope, $location,
$state, toastr, $timeout, $window) {
/* for drafts */
$scope.draft = {
draftType: '',
scheduledTime: '',
senderdata: '',
draftData: {
contacts: ''
},
groups: {
select: false
},
senderName: '',
message: '',
draftName: '',
createdOn: '',
updatedOn: ''
};
//add draft
$scope.addmanualInputDraft = function () {
$http.post('/api/addmanualinputdraft', $scope.draft).then(function (response) {
toastr.success("Added successfully!");
$('.bd-example-modal-lg-manual').modal('hide');
$state.reload();
});
}
})
My services.js:
angular
.module('sampleApp.services', [])
.factory('sharedService', function ($http) {
var draftPromise = $http({
method: 'GET',
url: '/api/getnewgroup'
});
return {
getDraftPromise: function () {
return draftPromise;
}
};
});
my app.js:
'use strict';
angular
.module('sampleApp', ['sampleApp.controllers', 'sampleApp.directives','sampleApp.services','sampleApp.filters','ui.router','toastr','ngSanitize', 'ui.select'])
.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.hashPrefix('');
$urlRouterProvider.otherwise('/dash');
$stateProvider
.state('dash', {
url: '/dash',
templateUrl: 'partials/dash',
})
.state('quicksms', {
url: '/quicksms',
templateUrl: 'partials/quicksms',
controller: 'quicksmsCtrl'
})
.state('professionalsms', {
url: '/professionalsms',
templateUrl: 'partials/professionalsms',
controller: 'profsmsCtrl'
})
.state('file2sms', {
url: '/file2sms',
templateUrl: 'partials/file2sms',
controller: 'file2smsCtrl'
})
.state('addressbook', {
url: '/addressbook',
templateUrl: 'partials/addressbook',
controller: 'addressbookCtrl'
})
});
This is updated full code. I want to access $scope.draft.groups object from addressbook Controller.
In general, you'd want to create a service that holds your shared data:
myApp.factory('sharedService', function($http) {
var draftPromise = $http({
method: 'GET',
url: '/api/getnewgroup'
});
return {
getDraftPromise: function() {
return draftPromise;
}
};
});
In your controllers, you can then use the service by declaring it as a dependency:
myApp.controller("myController", function($scope, sharedService) {
sharedService.getDraftPromise().then(function(response) {
$scope.draft.groups = response.data;
});
});
Both controllers will refer to the same instance of draftPromise.
Note: if you are minifying your code, you'll want to use the alternate syntax for dependency injection that uses arrays. Take a look at the official documentation for dependency injection.

Angular JS Service Creation Error

I have created this service.
and using **enrollments.getProperty();**this statement to call this service but it's not working I'm new to angular-JS please let me know where I making the mistake.
var helloAjaxApp = angular.module("myApp", []);
helloAjaxApp.service('enrollments', [ '$scope', '$http', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
var enrollments = null;
enrollment();
$scope.enrollment=function () {
$http({
url : 'enrollments',
method : "GET"
}).then(function(response) {
enrollments = response.data;
alert("enrollments");
});
};
return {
getProperty: function () {
return enrollments;
},
setProperty: function(value) {
enrollments = value;
}
};
}]);
use angular.module()
(function () {
'use strict';
angular.module("helloAjaxApp")
.service('enrollments', ['$scope', '$http', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
var enrollments = null;
enrollment();
$scope.enrollment = function () {
$http({
url: 'enrollments',
method: "GET"
}).then(function (response) {
enrollments = response.data;
alert("enrollments");
});
};
return {
getProperty: function () {
return enrollments;
},
setProperty: function (value) {
enrollments = value;
}
};
}]);
});
Angular has 2 ways of defining a service: service and factory.
here you can see the difference: https://blog.thoughtram.io/angular/2015/07/07/service-vs-factory-once-and-for-all.html
The basic difference is that service is like a constructor, so you don't return an object from it but define the properties using this keyword:
this.getProperty = function () {
return enrollments;
}
When using the factory method, is expects an object to be returned with the exposed properties/functions.
You are using the factory syntax, so just change the definition to use factory:
helloAjaxApp.factory('enrollments', [ '$scope', '$http', function ($scope, $http)
You should go for a proper service structure like so:
var helloAjaxApp = angular.module("myApp", []);
function EnrollmentService($scope, $http) {
let _this = this;
this.enrollments = null;
this.getEnrollments = function() {
return $http({
url: 'enrollments',
method: 'GET'
}).then(function(response) {
_this.enrollments = response.data;
return _this.enrollments;
})
};
this.setEnrollments = function(enrollments) {
_this.enrollments = enrollments;
}
}
helloAjaxApp.service('enrollments', ['$scope', '$http', EnrollmentService]);
Then, use the service anywhere else:
enrollmentService
.getEnrollments()
.then(function(enrollments) {
// You can use the data here.
console.log(enrollments);
});
The controller code
LoginService is service name you have to pass as a parameter to controller
var loginModule = angular.module('LoginModule',[]);
loginModule.controller('logincontroller', ['$rootScope','$scope','$http','$window','$cookieStore',
'LoginService',logincontrollerFun ]);
function logincontrollerFun($rootScope, $scope, $http, $window,$cookieStore, LoginService,RememberService) {
$scope.loginTest = function() {
LoginService.UserStatus($scope, function(resp) {
console.log("response of login controller ::: ", resp);
///write ur code
});
}
}
service code
var loginModule = angular.module('LoginModule')
loginModule.factory("LoginService",[ '$http', LoginServiceFun ])
function LoginServiceFun($http) {
function UserStatus($scope,callback){
var targetRequestPath='./url';
var targetRequestParamsREQ={'email':$scope.email,'password':$scope.passWord};
return $http({
method: 'POST',
url: targetRequestPath,
headers: {'Content-Type': 'application/json'},
data: targetRequestParamsREQ
}).then(function (response){
console.log('Response Data : ', response.data);
callback( response.data );
})
}
return {
UserStatus:UserStatus
}
}

How to pass $scope to $factory

Hi Im new in angular js and I want to pass my empty $scope to my $factory for the dynamic login im using the $http to get the data in my API i tried to put the scope in the factory but i didn't work
This is my serviceAPI
(function() {
"use strict";
angular.module('starter').factory(serviceAPI', function($http, $q, $ionicLoading, $timeout) {
function getData() {
var deferred = $q.defer();
$ionicLoading.show({ template: 'Loading...' });
var url = "myAPI";
var data = {
username: "admin", <-- this is the one I want to dynamic it
password: "admin" <--
};
$http({
method: 'POST',
url: url,
data: data
}).success(function(data) {
$ionicLoading.hide();
deferred.resolve(data);
}).error(function() {
console.log('Error while making HTTP call');
$ionicLoading.hide();
deferred.reject();
});
return deferred.promise;
}
//a Return value to public
return {
getData: getData,
};
})
}());
this is the controller
(function() {
"use strict";
angular.module('starter').controller('LoginCtrl', ['$scope', 'serviceAPI', LoginCtrl]);
function LoginCtrl($scope, serviceAPI) {
$scope.username = "";
$scope.password = "";
$scope.login = function() {
serviceAPI.getData().then(function(data) {
console.log(data)
});
}
}
}());
at service api
function getData(userNameIn, passwordIn) {
//...
var data = {
username: userNameIn,
password: passwordIn
}; //...}
at controller
...
$scope.username = "";
$scope.password = "";
$scope.login = function() {
serviceAPI.getData($scope.username,$scope.password).then(function(data) {
console.log(data)
});
}
...

Send a JS variable to a specific Symfony route

I have a Symfony 3 project with Angular JS in front.
The project is about taking an URL with specific XML content, send it to SF3, do some manipulation, and send the final result to Angular JS.
I just want to catch my url variable in my Symfony Controller.
app.js
var app = angular.module("test", []);
app.controller("testCtrl", ['$scope', '$http', '$window', function($scope, $http, $window) {
$scope.getMyXML = function() {
$http.get($scope.urlSubmitted)
.success(function(data, status, headers, config) {
$http({
method: 'POST',
url: Routing.generate('f_api'), //FOSJsRoutingBundle
headers: {},
params: {},
data: {urlToParse:$scope.urlSubmitted}
}).then(function successCallback(response) {
console.log('Sended to SF3');
}, function errorCallback(response) {
console.log('NOT sended to sf2');
});
})
.error(function(data, status, headers, config) {
alert('!! XML GET ERROR !!');
})
}
}]);
Symfony controller action
class MyController extends Controller
{
public function indexAction(Request $request)
{
$serializer = $this->get('jms_serializer');
$data = $request->request->get('urlToParse');
//var_dump($data);
//die;
return $this->render('MyBundle:My:index.html.twig');
}
public function apiAction(Request $request)
{
$data = $request->request->get('urlToParse');
var_dump($data);
die;
return new JsonResponse();
}
}
And last, my routing.yml
f_home:
path: /
defaults: { _controller: MyBundle:My:index }
f_api:
path: /api/
defaults: { _controller: MyBundle:My:api }
options:
expose: true
The apiAction is never lanched, despite of the angular http post on it...
Thanks !
Try this:
data: {'urlToParse':$scope.urlSubmitted}
then:
$data = $request->request->get('urlToParse');

Categories