How to pass $scope to $factory - javascript

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)
});
}
...

Related

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 do I convert a controller http call to a Service/factory pattern that takes in a parameter

I have a controller that is calling http.get, http.push and http.post methods.
I am learning angularjs and have found that it's best to call your http.get in your service file. I am able to do that with a simple http.get, but get confused with a http.get by id or http.get/http.post which takes a parameter:
My current controller looks like this
angular.module("app-complaints")
.controller("clcontrol", clcontrol);
function clcontrol($routeParams, $http, $scope) {
$http.get(baseURL + "/api/complaints/" + $scope.complaintCase + "/checklists")
.then(function (cl) {
//success
$scope.index = 0;
$scope.cl = [];
$scope.cl = cl;
}
I want to separate it out like this
controller.js
angular.module("app-complaints")
.controller('clcontrol', function ($http, $scope, $q, Service, $timeout) {
....
getCL();
function getCL(){
Service.getCl()
.success(function(cl){
$scope.cl = [];
$scope.cl = cl;
}
service.js
angular.module("app-complaints")
.factory('Service', ['$http', function ($http) {
Service.getCL = function () {
return $http.get(urlBase + "/api/complaints/" + complaintCase + "/checklists")
};
};
Simple. Make a factory that accepts parameters.
var app = angular.module("MyApp", [ /* dependencies */]);
app.factory("SharedServices", ["$http", function($http) {
return {
getItems: function(url, parameters) {
return $http.get(url, {
//optional query string like {userId: user.id} -> ?userId=value
params: parameters
});
},
postItem: function(url, item) {
var payload = {
item: item
};
return $http.post(url, payload);
},
deleteItem: function(url, item) {
var payload = {
item: item
};
return $http({
url: url,
data: payload,
method: 'DELETE',
});
}
// ETC. ETC. ETC.
// follow this pattern for methods like PUT, POST, anything you need
};
}]);
Use the service in your controller:
app.controller("MainCtrl", ["$scope","SharedServices", function($scope, SharedServices) {
//do things with the shared service
$scope.postMyThings = function() {
SharedServices.postItems('path/to/api', itemsArray).then(function(response) {
//success callback, do something with response.data
}, function(response) {
//an error has occurred
});
};
$scope.getMyThing = function() {
SharedServices.getItems('path/to/api/get').then(function(response) {
//success callback, do something with response.data
}, function(response) {
//an error has occurred
});
}
}]);

service does not return data to controller in angular

Here is my service:
app.service('trackService', ['$http', function($http) {
var data;
this.topTracks = function(limit) {
$http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json', limit: limit}
}).success(function(result) {
this.data = result.tracks; console.log(this.data); return this.data;
});
}
}]);
and controller -
app.controller('artistSongsCtrl', ['$scope', 'trackService', function($scope, trackService) {
$scope.data = trackService.topTracks(10);
//console.log($scope.data);
}]);
how to send data to the controlller using a $http service inside a custom service?
Several problems are $http is asynchronous and your service method topTracks() doesn't return anything. Also you can't return inside success, there is nowhere to return to ... use then() instead
You need to return the promise from service and set the scope in a promise callback in controller
app.service('trackService', ['$http',
function($http) {
var data;
var self = this;
this.topTracks = function(limit) {
return $http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
params: {
api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf',
format: 'json',
limit: limit
}
}).then(function(result) {
self.data = result.data.tracks;
console.log(self.data);
return self.data;
});
}
}
]);
app.controller('artistSongsCtrl', ['$scope', 'trackService',
function($scope, trackService) {
trackService.topTracks(10).then(function(data) {
$scope.data = data;
//console.log($scope.data);
});
}
]);
Inside your service you are making an asynchronous GET request. In order to let the controller catch that response, you need to return a promise. Here's an example using $q:
app.service('trackService', ['$http', '$q', function($http, $q) {
var data;
this.topTracks = function(limit) {
var d = $q.defer();
$http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json', limit: limit}
}).success(function(result) {
this.data = result.tracks;
console.log(this.data);
d.resolve(this.data);
});
return d.promise;
}
}]);

Using Parse.com REST-API with AngularJS

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");
})
}
}]);

AngularJS: Performing $http request inside custom service and returning data

I have defined a custom http service in angular that looks like this:
angular.module('myApp')
.factory('myhttpserv', function ($http) {
var url = "http://my.ip.address/"
var http = {
async: function (webService) {
var promise = $http.get(url + webService, { cache: true }).then(function (response) {
return response.data;
});
return promise;
}
};
return http;
});
And I can access this service in my controller like so:
angular.module('myApp')
.controller('myCtrl', function (myhttpserv) {
var webService = 'getUser?u=3'
myhttpserv.async(webService).then(function (data) {
console.log(data);
})
});
However I now need to streamline this process so that it is ALL contained inside the service with a static url and it simply returns the data. So that I can just call it in the controller like so:
angular.module('myApp')
.controller('myCtrl', function ($scope, myhttpserv) {
console.log(myhttpserv.var1);
console.log(myhttpserv.var2);
etc...
});
I can't seem to tweak the service to get this functionality. Anyone know the correct way to do it?
Option 1 - Use promise API
angular.module('myApp').factory('myhttpserv', function ($http) {
return $http.get('http://my.ip.address/getUser?u=3', { cache: true });
});
Controller:
angular.module('myApp').controller('myCtrl', function ($scope, myhttpserv) {
myhttpserv.then(function(response){
console.log(response.data);
});
});
Option 2 - Using route resolve
angular.module('myApp', ['ngRoute']).config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/myCtrl', {
templateUrl: 'myView.html',
controller: 'myCtrl',
resolve: {
load: function (myhttpserv) {
return myhttpserv;
}
});
}]);
Service:
angular.module('myApp').factory('myhttpserv', function ($http) {
var data = {};
var url = "http://my.ip.address/";
var promise = $http.get(url + 'getUser?u=3', { cache: true }).then(function (response) {
data = response.data;
});
return data;
});
Controller:
angular.module('myApp')
.controller('myCtrl', function ($scope, myhttpserv) {
console.log(myhttpserv.data.var1);
console.log(myhttpserv.data.var1);
etc...
});
Option 3 - Use $interval service
angular.module('myApp').factory('myhttpserv', function ($http) {
var data = {};
var url = "http://my.ip.address/";
var promise = $http.get(url + 'getUser?u=3', { cache: true }).then(function (response) {
data = response.data;
});
return data;
});
Controller:
angular.module('myApp').controller('myCtrl', function ($scope, $interval, myhttpserv) {
$scope.intervalPromise = $interval(function(){
if (Object.keys(myhttpserv.data).length!=0)
{
console.log(myhttpserv.data);
$interval.cancel($scope.intervalPromise);
}
}, 100);
});

Categories