Refactoring Angular controller into separate factory and controller - javascript

Learning Angular. Working with 1.6.6 right now.
In my initial stab, I put all my $http requests into my controller, so I'm trying to pull that out of the controller and into a factory for more reusable code. I think that I am missing something related to Promise or injection, but the data from my $http call is not being bound to $scope correctly.
I've been following along this guide.
I have a template that's begin loaded from the controller (the template is loading fine):
<form ng-init="getAllRegions()" ng-submit="getRandomTown()">
<h3>Generate Random Town</h3>
<div class="form-group-row">
<label for="selectRegion">Select Region:</label>
<select name="nameEntity"
id="selectRegion"
ng-model="guidEntity"
ng-options="item.guidEntity as item.nameEntity for item in regions">
<option value="" ng-if="!guidEntity"></option>
</select>
</div>
</form>
The ng-init function is being called, and passes through the controller and the service. In chrome inspector I can see that data is pulling through correctly, but I'm new to working with Promises, so I'm losing something along the way. This was all working as expected when the $http call was right in the controller and the data was being bound to $scope in the controller.
The controller:
angular.
module('randomTown.controller', []).
component('randomTownGenerator', {
templateUrl: 'js/components/randomTownGenerator/randomTownGenerator.tpl.html'
}).
controller('RandomTownCtrl',
function($scope, randomTownFactory) {
$scope.data = {};
$scope.getAllRegions = function () {
$scope.regions = randomTownFactory.getAllDBRegions();
}
}
);
The service:
angular.
module('randomTown.service', []).
factory('randomTownFactory', function ($q, $http) {
var service = {};
service.getAllDBRegions = function() {
var deferred = $q.defer();
$http({
method: 'GET',
url: '/all-regions'
}).then(function success(data) {
deferred.resolve(data);
}), function error(response) {
deferred.reject('There was an error');
}
return deferred.promise;
}
return service;
});

There is no need to manufacture a promise with $q.defer. Simply return the $http promise:
app.factory('randomTownFactory', function ($q, $http) {
var service = {};
service.getAllDBRegions = function() {
̶v̶a̶r̶ ̶d̶e̶f̶e̶r̶r̶e̶d̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
̲r̲e̲t̲u̲r̲n̲ $http({
method: 'GET',
url: '/all-regions'
}).then(function success( ̶d̶a̶t̶a̶ response) {
̶d̶e̶f̶e̶r̶r̶e̶d̶.̶r̶e̶s̶o̶l̶v̶e̶(̶d̶a̶t̶a̶)̶;̶
return response.data;
}),̶ ̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶e̶r̶r̶o̶r̶(̶r̶e̶s̶p̶o̶n̶s̶e̶)̶ ̶{̶
̶d̶e̶f̶e̶r̶r̶e̶d̶.̶r̶e̶j̶e̶c̶t̶(̶'̶T̶h̶e̶r̶e̶ ̶w̶a̶s̶ ̶a̶n̶ ̶e̶r̶r̶o̶r̶'̶)̶;̶
̶}̶
̶r̶e̶t̶u̶r̶n̶ ̶d̶e̶f̶e̶r̶r̶e̶d̶.̶p̶r̶o̶m̶i̶s̶e̶;̶,
}
return service;
});
Also notice that the success handler does not reveal the data. It reveals a response object of which data is one of the properties.
The controller:
app.controller('RandomTownCtrl',
function($scope, randomTownFactory) {
$scope.getAllRegions = function () {
var promise = randomTownFactory.getAllDBRegions();
promise.then(function(data) {
$scope.regions = data;
}).catch(function(errorResponse) {
console.log("ERROR", errorResponse.status)
});
}
}
);
For more information, see
AngularJS $http service API Reference
You're Missing the Point of Promises

Try this:
$scope.getAllRegions = function () {
randomTownFactory.getAllDBRegions()
.then((regions) => {$scope.regions = regions});
}
Why: because etAllDBRegions returns a promise, so you have to use then property to get the result

Related

How should I set data from an asynchronous service into a controller $scope?

All server data accesses in my page are performed by my RequestFactory provider.
(The RequestFactory uses $http to perform the actual server calls.)
My controller scope has a reference to the list of data returned from the RequestFactory.
My question is that since the RequestFactory calls are asynchronous, and the RequestFactory does not (and should not) have access to the controller scope, what is the proper way for the RequestFactory to hand off the data to the controller?
var requestFactory = {};
angular.module("myApp").factory("RequestFactory", function($http) {
requestFactory.fetch = function() {
$http.get(url).
success(function(data) {
controller.setData(data)
}).
error(function(data, status) {
console.info("fetch Failed. Error code: " + status + " Url:" + url);
}).finally(function() {
controller.setSubmitting(false);
});
};
return requestFactory;
});
You should return the promise from you factory. See below snippet.
.factory("RequestFactory", function($http) {
return {
fetch : function() {
return $http.get(url).then(function(result) {
return result.data;
});
}
}
});
In your controller you should use like
.controller('MainCtrl', function($scope, RequestFactory) {
RequestFactory.fetch().then(function(data)
$scope.foo = data;
});
});
You can do the following :
Service
(function(){
function Service($http){
function get(){
//We return a promise
return $http.get('path_to_url');
}
var factory = {
get: get
};
return factory;
}
angular
.module('app')
.factory('Request', Service);
})();
Controller
(function(){
function Controller($scope, $q, Request) {
var defer = $q.defer();
//Call our get method from the Request Factory
Request.get().then(function(response){
//When we get the response, resolve the data
defer.resolve(response.data);
});
//When the data is set, we can resolve the promise
defer.promise.then(function(data){
console.log(data);
});
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
As you know, $http service return promise, so after that, you can easily combining them.

How to use a service with Http request in Angular JS

I'm using AngularJS to build my web application, I've been always using controllers to make HTTP request, which makes things easier and clear for me.
But for a better code structure, and better execution for my application, I wanted to use services instead of controllers to use the web service.
I tried to make :
var app = angular.module('ofcservices', []);
app.factory('news', ['$http', function ($http) {
var news={};
news.getnews= function () {
return $http.get('http://int.footballclub.orange.com/ofc/news?offset=0&limit=5');
};
return news;
}]);
and the code of the controller :
.controller('news', function($scope, ofcservices) {
$scope.news = ofcservices.getnews();
})
Everything seems to be right ?
ofcservices.getnews() is a promise You need manage with the function sucess and error
ofcservices.getnews().
success(function(data) {
$scope.news=data
}).
error(function(data, status, headers, config) {
//show a error
});
As weel change app.factory('news' to app.factory('newsFactory' and call it in controller('news', function($scope, newsFactory) {
You can get more data about promise in the angular documentation
The concept is more or less right, but you should use the callback functions to handle the $http response correctly.
But your controller and service have the same name news, which is BAD :-) and you need to inject the newsService and not the module name.
.controller('newsController', function($scope, newsService) {
newsService.getnews().then(
function(newsData) {
$scope.newsData = newsData
},
function optionalErrorhandler() {});
})
angular
.module('MyApp', [])
.controller('MyController', MyController)
.factory('MyService', MyService);
MyController.$inject = ['$scope','MyService'];
MyService.$inject = ['$http'];
function MyService($http){
var service = {
var myServiceFunction : function(){
$http({
// your http request on success return the data.
}).success(function(data)){
return data;
});
}
};
return service;
}
function MyController($scope, MyService){
MyService.myServiceFunction(); //Call service from the controller.
}

How to view json data from angularjs http callback?

I can see my json data in the console and I want to view it on html page after clickbutton function. From my understaning I can either do a promise ($q) or then with http or ngResource. First I want to do http then migrate to ngResource. For some reason my scope is still undefined. Maybe it's a ng-init or ng-repeat I'm missing? Any ideas?
var app = angular.module('myApp', []);
app.factory('httpq', function($http, $q) {
return {
get: function() {
var deferred = $q.defer();
$http.get.apply(null, arguments)
.success(deferred.resolve)
.error(deferred.resolve);
return deferred.promise;
}
}
});
app.controller('myController', function($scope, httpq) {
httpq.get('http://localhost:8080/states')
.then(function(data) {
$scope.returnedData = data;
})
$scope.clickButton = function() {
$scope.returnedData;
}
});
view
<div data-ng-controller="myController">
<button data-ng-click="clickButton()">Get Data From Server</button>
<p>JSON Data : {{returnedData}}</p>
</div>
Use Ajax call
Service:
var demoService = angular.module('demoService', [])
.service('myService',['$http', function($http) {
this.getdata = function(entity){
var promise = $http({
method : 'POST',
url : 'services/entity/add',
data : entity,
headers : {
'Content-Type' : 'application/json'
},
cache : false
}).then(function (response) {
return response;
});
return promise;
};
}]);
Controller :
var demoService = angular.module('demoService', [])
.controller('myctr',['$scope','myService',function($scope,myService){
myService.getdata().then(function(response){
//Success
},function(response){
//Error
});
}]);
now you can see your json in controller success
$http itself is a promise, no need to create a new promise. Just return the $http.get wihoit the success written there and right the sucess fn in the controller itself. So your code will look like this:
app.factory('httpq', function($http) {
return {
get: function() {
return $http.get.apply(null, arguments);
}
}
});
Your controller:
app.controller('myController', function($scope, httpq) {
httpq.get('http://localhost:8080/states').then(function(data) {
$scope.returnedData = data;
})
$scope.clickButton = function() {
$scope.returnedData;
}
});
use
$scope.returnedData=JSON.parse(data);
It will give you values in JSON format
I have not worked with promise. But your factory code seems to be ok.
In controller declare your object first.
If it's just object declare it as
$scope.returnedData = {};
If it's array, declare it as
$scope.returnedData = [];
The the object will not be undefined and changes will affect in HTML

how do i pass scope from controller to service in angularjs?

I have the following controller:
'use strict';
/* Controllers */
angular.module('stocks.controllers', []).
controller('MyCtrl1', ['$scope', '$http', 'stockData', function MyCtrl1 ($scope, $http, stockData) {
$scope.submit = function() {
$scope.info = stockData.query();
console.dir($scope.info);
}
}]);
and i want to pass a bound ng-model that sits in my view called ng-model="symbol_wanted" to the following service...
'use strict';
/* Services */
angular.module('stocks.services', ['ngResource']).factory('stockData', ['$resource',
function($resource){
return $resource('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json', {}, {
query: {method:'GET', isArray:false}
});
}]);
how do i connect the controller's scope to get passed into the service? thanks!
how do i pass scope from controller to service in angularjs?
You can't inject $scope into services, there is no such thing as a Singleton $scope.
i want to pass a bound ng-model that sits in my view called ng-model="symbol_wanted" to the following service...
You can call the service and pass parameters this way:
.factory('stockData', ['$resource', '$q', function ($resource, $q) {
var factory = {
query: function (value) {
// here you can play with 'value'
var data = $resource('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json', {}, {
query: {
method: 'GET',
isArray: false
}
});
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);
So we call this service and get a promise back like this:
stockData.query(value) // <-- pass value
.then(function (result) {
$scope.data = result;
}, function (result) {
alert("Error: No data returned");
});
BTW, I'd suggest you use $http.get:
Demo Fiddle
Your ng-model value will automatically become a scope property. So, you can just use this in your controller to get the current value:
$scope.symbol_wanted;
So, let's say that you have a function to handle the click in your controller:
$scope.handleMyClick = function() {
stockData.query($scope.symbol_wanted);
}
You can just use the scoped property.

Angular.js delaying controller initialization

I would like to delay the initialization of a controller until the necessary data has arrived from the server.
I found this solution for Angular 1.0.1: Delaying AngularJS route change until model loaded to prevent flicker, but couldn't get it working with Angular 1.1.0
Template
<script type="text/ng-template" id="/editor-tpl.html">
Editor Template {{datasets}}
</script>
<div ng-view>
</div>
​
JavaScript
function MyCtrl($scope) {
$scope.datasets = "initial value";
}
MyCtrl.resolve = {
datasets : function($q, $http, $location) {
var deferred = $q.defer();
//use setTimeout instead of $http.get to simulate waiting for reply from server
setTimeout(function(){
console.log("whatever");
deferred.resolve("updated value");
}, 2000);
return deferred.promise;
}
};
var myApp = angular.module('myApp', [], function($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/editor-tpl.html',
controller: MyCtrl,
resolve: MyCtrl.resolve
});
});​
http://jsfiddle.net/dTJ9N/1/
Since $http returns a promise, it's a performance hit to create your own deferred just to return the promise when the http data arrives. You should be able to do:
MyCtrl.resolve = {
datasets: function ($http) {
return $http({method: 'GET', url: '/someUrl'});
}
};
If you need to do some processing of the result, use .then, and your promise is chained in for free:
MyCtrl.resolve = {
datasets: function ($http) {
return $http({method: 'GET', url: '/someUrl'})
.then (function (data) {
return frob (data);
});
}
};
You could always just put "ng-show" on the outer-most DOM element and set it equal to the data you want to wait for.
For the example listed on the Angular JS home page you can see how easy it is: http://plnkr.co/CQu8QB94Ra687IK6KgHn
All that had to be done was
That way the form won't show until that value has been set.
Much more intuitive and less work this way.
You can take a look at a near identical question here that uses resources, but it works the same way with $http. I think this should work
function MyCtrl($scope, datasets) {
$scope.datasets = datasets;
}
MyCtrl.resolve = {
datasets: function($http, $q) {
var deferred = $q.defer();
$http({method: 'GET', url: '/someUrl'})
.success(function(data) {
deferred.resolve(data)
}
return deferred.promise;
}
};
var myApp = angular.module('myApp', [], function($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/editor-tpl.html',
controller: MyCtrl,
resolve: MyCtrl.resolve
});
});​

Categories

Resources