guys
I'm new to Angularjs, here's some code of my new single-page app. But I think I'm not doing it right.
Here is my gode:
var TownApp=angular.module('TownApp',['ngRoute','ngResource']);
TownApp.service('Town', function($http) {
this.all = function() {
return $http.get('/database.json').then(function(response){
return response.data;
})
};
});
var HomeCtrl = TownApp.controller('HomeCtrl',function($scope,Town){
$scope.towns = Town.all();
});
var TownCtrl = TownApp.controller('TownCtrl',function($scope, $routeParams, Town){
console.log(Town.all().length)
$scope.towns = Town.all();
console.log($scope.towns.length)
//........
})
TownApp.config(['$routeProvider', function($routes) {
$routes.when('/',{
templateUrl : 'welcome.html',
controller : 'HomeCtrl'
}).when('/town/:townId',{
templateUrl : 'town.html',
controller : 'TownCtrl'
}).otherwise({
redirectTo : '/'
});
}]);
So, the question is you can see those two console logs in Town controller, they all returned 'undefined'. So that I can't iterate or get values from Town.all(). But its working perfect on HomeController.
I've treid with both service and factory. I think I'm just doing it in wrong way?
Thanks for your help!
Your mistake is that you try to retrieve the data from the server in a synchronous way, which doesn't work in angular (nor in javascript in general).
Change the service code to:
TownApp.service('Town', function($http) {
this.all = function() {
return $http.get('/database.json');
};
});
And then change the controller code to:
TownApp.controller('HomeCtrl',function($scope,Town){
Town.all().then(function(response)) {
$scope.towns = response.data;
console.log($scope.towns.length);
}
}
Town.all() returns a promise. A promise is like a value to be returned some time in the future. It's not directly the value. It's an object that can be used to retrieve the value.
So instead of
$scope.towns = Town.all();
you need:
Town.all()
.then(function(response){
//if the promise we are dealing with is the promise that was directly
//returned from the $http call, then we need response.data
//if it was projected to hold `response.data` before (as in the initial question)
//then "response" here is already holding our data.
$scope.towns = response;
});
Related
I've checked several solutions on the web but I don't quite understand how to stop the controllers from loading. So, I've created a plunkr to highlight what I want to do.
Basically: I want to load all data in a service and then pass around that data from that service to each controller. When the app first loads, because it's Async, the controllers are loaded first.
I could have just used the factory in each controller, but I want to hold that data in the "allProducts" property of the service. I don't see the need to call the factory function each time a view loads.
In the example, I've also tried with the $q service, but seems to me it has the same behaviour just like the http from the factory and still needs to call the http request on each view load...
So, could somebody help me with this example and implement an elegant solution?
app.factory('productsFactory', ['$http', '$q',
function($http, $q) {
var cachedData; //here we hold the data after the first api call
function getData(callback) {
if (cachedData) {
callback(cachedData);
} else {
$http.get('http://api.bestbuy.com/v1/products(longDescription=iPhone*|sku=7619002)?show=sku,name&pageSize=15&page=5&apiKey=bqs7a4gwmnuj9tq6bmyysndv&format=json')
.success(function(data) {
cachedData = data; //caching the data in a local variable
callback(data);
});
}
}
return {
getProds: getData
}
}
])
app.service('appService', ['productsFactory', '$q',
function(productsFactory, $q) {
var _this = this;
productsFactory.getProds(function(data) {
_this.allProducts = data; //wait for data to load before loading the controllers
})
}
])
app.controller('productsCtrl', ['$scope', 'appService',
function($scope, appService) {
$scope.myProducts = appService.allProducts;
}
]);
plunkr here: http://plnkr.co/edit/ZvtYwXHSasC3fCAZKkDF?p=preview
I didn't actually test it, but looks like you need to create and return a promise in order to have the data returned when it's available.
app.factory('productsFactory', ['$http', '$q',
function($http, $q) {
var cachedData; //here we hold the data after the first api call
function getData(callback) {
var d = $q.defer();
if (cachedData) {
d.resolve(callback(cachedData));
} else {
$http.get('http://api.bestbuy.com/v1/products(longDescription=iPhone*|sku=7619002)?show=sku,name&pageSize=15&page=5&apiKey=bqs7a4gwmnuj9tq6bmyysndv&format=json')
.success(function(data) {
cachedData = data; //caching the data in a local variable
d.resolve(callback(cachedData));
});
}
return d.promise;
}
return {
getProds: getData
}
}
])
app.service('appService', ['productsFactory', '$q',
function(productsFactory, $q) {
var _this = this;
productsFactory.getProds(function(data) {
_this.allProducts = data; //wait for data to load before loading the controllers
})
}
])
app.controller('productsCtrl', ['$scope', 'appService',
function($scope, appService) {
$scope.myProducts = appService.allProducts;
}
]);
Check this: http://plnkr.co/edit/ey0na3l2lyT0tUdbDyrf?p=preview
Changes:
- a main app controller that wraps all your app.
In this controller we prevent route change if the boot hasn't finished all its jobs. When boot is finished, we change location to the main/default route.
- in our run block we set the bootStatus var to false and wait until products are fetch.
Also, I've stored the result from service to $rootScope so you can use that data in all your controllers without injecting the service over and over again.
FINALLY!!! I Managed to do what I was looking for.
Note, this is not necessarily a best practice, but it was a problem that was bugging me and wanted to know how it's done.
The way I did it was to create a global variable, where I use a main resolve function to wait for the factory to do the http get and then pass it to the service. Then, I use resolve on every state where I need that data and reference that function.
UPDATE: Realized that I was calling the same factory function each time the state was changins, so I decided to go with a variable - a property in the appService which turns to true when the http get was called once: appService.retrieved and changed the main resolve function a bit.
var mainResolve = ['$q', 'appService', 'productsFactory', function($q, appService, productsFactory) {
var defer = $q.defer();
if(appService.retrieved) {
defer.resolve();
} else {
productsFactory.getProds(function(data) {
appService.allProducts = data;
defer.resolve();
})
appService.retrieved = true;
}
return defer.promise;
}]
And in the state
.state('home', {
url: "/home",
templateUrl: "home.html",
controller: 'homeCtrl',
resolve: {
waitingFor: mainResolve
}
})
You can find the plnkr with the working solution, here: http://plnkr.co/edit/ZvtYwXHSasC3fCAZKkDF?p=preview
Again, the factory could be refactored some more and eliminate some code like the caching data. This way, we only go once to the factory function.
I'm looking for some information on the best way to retrieve data from a local JSON file and handle the response. After browsing through Stack Overflow, I have some mixed thoughts as I've seen multiple ways of doing the same thing (although no explanation on why one may or may not be preferred).
Essentially, I have an Angular app that is utilising a factory to retrieve data from a JSON file; I'm then waiting for the response to resolve in my controller before using it in my html file, similar to the below:
Option 1
Factory:
comparison.factory('Info', ['$http', function($http) {
var retrievalFile = 'retrievalFile.json';
return {
retrieveInfo: function() {
return $http.get(retrievalFile);
}
}
}]);
Controller:
comparison.controller('comparisonController', ['$scope', 'Info', function($scope, Info) {
Info.retrieveInfo().then(function(response) {
$scope.info = response.data;
});
}]);
My main point of contention is figuring out when it's best to wait for the response to resolve, or if it even matters. I'm toying with the idea of having the factory return the fulfilled promise, and wait for the controller to retrieve the data also. In my view, it's best to abstract all data retrieval out of the controller and into the factory, but I'm not sure if this extends to waiting for the actual data to be returned within the factory itself. With this in mind, I'm confused about whether to opt for option 1 or option 2 and would really appreciate some feedback from more experienced/qualified developers!
Option 2
Factory:
comparison.factory('Info', ['$http', function($http) {
var retrievalFile = 'retrievalFile.json';
return {
retrieveInfo: function() {
return $http.get(retrievalFile).then(function(response) {
return response.data;
});
}
}
}]);
Controller:
comparison.controller('comparisonController', ['$scope', 'Info', function($scope, Info) {
Info.retrieveInfo().then(function(response) {
$scope.info = response;
});
}]);
Thank you for any input/suggestions in advance!
It depends on what your controller is expecting and how you set up your application. Generally, I always go with the second option. Its because I usually have global error or success handlers in all api requests and I have a shared api service. Something like below.
var app = angular.module('app', []);
app.service('ApiService', ['$http', function($http) {
var get = function(url, params) {
$http.get(url, { params: params })
.then(handleSuccess, handleError);
};
// handle your global errors here
// implementation will vary based upon how you handle error
var handleError = function(response) {
return $q.reject(response);
};
// handle your success here
// you can return response.data or response based upon what you want
var handleSuccess = function(response) {
return response.data;
};
}]);
app.service('InfoService', ['ApiService', function(ApiService) {
var retrieveInfo = function() {
return ApiService.get(retrievalFile);
/**
// or return custom object that your controller is expecting
return ApiService.get.then(function(data) {
return new Person(data);
});
**//
};
// I prefer returning public functions this way
// as I can just scroll down to the bottom of service
// to see all public functions at one place rather than
// to scroll through the large file
return { retrieveInfo: retrieveInfo };
}]);
app.controller('InfoController', ['InfoService', function(InfoService) {
InfoService.retrieveInfo().then(function(info) {
$scope.info = info;
});
}])
Or if you are using router you can resolve the data into the controller. Both ngRouter and uiRouter support resolves:
$stateProvider.state({
name: 'info',
url: '/info',
controller: 'InfoController',
template: 'some template',
resolve: {
// this injects a variable called info in your controller
// with a resolved promise that you return here
info: ['InfoService', function(InfoService) {
return InfoService.retrieveInfo();
}]
}
});
// and your controller will be like
// much cleaner right
app.controller('InfoController', ['info', function(info) {
$scope.info = info;
}]);
It's really just preference. I like to think of it in terms of API. What is the API you want to expose? Do you want your controller to receive the entire response or do you want your controller to just have the data the response wraps? If you're only ever going to use response.data then option 2 works great as you never have to deal with anything but the data you're interested in.
A good example is the app we just wrote where I work. We have two apps: a back-end API and our front-end Angular application. We created an API wrapper service in the front-end application. In the service itself we place a .catch for any of the API endpoints that have documented error codes (we used Swagger to document and define our API). In that .catch we handle those error codes and return a proper error. When our controllers/directives consume the service they get back a much stricter set of data. If an error occurs then the UI is usually safe to just display the error message sent from the wrapper service and won't have to worry about looking at error codes.
Likewise for successful responses we do much of what you're doing in option 2. In many cases we refine the data down to what is minimally useful in the actual app. In this way we keep a lot of the data churning and formatting in the service and the rest of the app has a lot less to do. For instance, if we need to create an object based on that data we'll just do that in return the object to the promise chain so that controllers aren't doing that all over the place.
I would choose option two, as it your options are really mostly the same. But let see when we add a model structure like a Person suppose.
comparison.factory('Info', ['$http', function($http) {
var retrievalFile = 'retrievalFile.json';
return {
retrieveInfo: function() {
return $http.get(retrievalFile).then(function(response) {
//we will return a Person...
var data = response.data;
return new Person(data.name, data.age, data.gender);
});
}
}
}]);
This is really simple, but if you have to map more complex data into object models (you retrieve a list of people with their own items... etc), that's when things get more complicated, you will probably want to add a service to handle the mapping between data and models. Well you have another service DataMapper(example), if you choose your first option you will have to inject DataMapper into your controller and you will have to make your request through your factory, and map the response with the injected service. And then you probably say, Should I have all this code here? ... Well probably no.
That is an hypothetical case, something that count a lot is how you feel structuring your code, won't architecture it in a way you won't understand. And at the end take a look at this: https://en.wikipedia.org/wiki/SOLID_(object-oriented_design) and research more information about this principles but focused to javascript.
Good question. A couple of points:
Controllers should be view centric versus data centric therefore you
want remove data logic from the controller and rather have it focus
on business logic.
Models (M in MVC) are a data representation of your application and
will house the data logic. In Angular case this would be a service
or factory class as you rightfully pointed out. Why is that well for
example:
2.1 AccountsController (might have multiple data models injected)
2.1.1 UserModel
2.1.2 AuthModel
2.1.3 SubscriptionModel
2.1.4 SettingsModel
There are numerous ways to approach the data model approach, but I would say your service class should be the data REST model i.e. getting, storing, caching, validating, etc. I've included a basic example, but suggest you investigate JavaScript OOP as that will help point you in the right direction as to how to build data models, collections, etc.
Below is an example of service class to manage your data.Note I have not tested this code but it should give you a start.
EXAMPLE:
(function () {
'use strict';
ArticleController.$inject = ['$scope', 'Article'];
function ArticleController($scope, Article) {
var vm = this,
getArticles = function () {
return Article.getArticles()
.then(function (result) {
if (result) {
return vm.articles = result;
}
});
};
vm.getArticles = getArticles;
vm.articles = {};
// OR replace vm.articles with $scope if you prefer e.g.
$scope.articles = {};
$scope.userNgClickToInit = function () {
vm.getArticles();
};
// OR an init on document ready
// BUT to honest I would put all init logic in service class so all in calling is init in ctrl and model does the rest
function initArticles() {
vm.getArticles();
// OR chain
vm.getArticles()
.then(getCategories); // doesn't here, just an example
}
initArticles();
}
ArticleModel.$inject = ['$scope', '$http', '$q'];
function ArticleModel($scope, $http, $q) {
var model = this,
URLS = {
FETCH: 'data/articles.json'
},
articles;
function extract(result) {
return result.data;
}
function cacheArticles(result) {
articles = extract(result);
return articles;
}
function findArticle(id) {
return _.find(articles, function (article) {
return article.id === parseInt(id, 10);
})
}
model.getArticles = function () {
return (articles) ? $q.when(articles) : $http.get(URLS.FETCH).then(cacheArticles);
};
model.getArticleById = function (id) {
var deferred = $q.defer();
if (articles) {
deferred.resolve(findArticle(id))
} else {
model.getBookmarks().then(function () {
deferred.resolve(findArticle(id))
})
}
return deferred.promise;
};
model.createArticle = function (article) {
article.id = articles.length;
articles.push(article);
};
model.updateArticle = function (bookmark) {
var index = _.findIndex(articles, function (a) {
return a.id == article.id
});
articles[index] = article;
};
model.deleteArticle = function (article) {
_.remove(articles, function (a) {
return a.id == article.id;
});
};
}
angular.module('app.article.model', [])
.controller('ArticleController', ArticleController)
.service('Article', ArticleModel);
})()
I'm trying to move my logic from controllers to Services, as I am still am new to AngularJS.
I'm trying to get some data from an internal API and return it to my Controller's scope, though the way I am doing it is returning an empty Object.
Here is my controller.
cbApp.controller('serversCtrl', function($scope, serversService){
$scope.servers = serversService.getServers();
console.log($scope.servers); // returns Object {}
});
And here is my service, which I am probably doing wrong.
cbApp.service('serversService', function($http){
var servers = {}
this.getServers = function(){
$http.get(BASE_URL + '/api/s').success(function(response){
servers = response.servers;
});
return servers;
}
});
Seems like servers = response.servers isn't getting attached after the get function.
What am I doing wrong?
Your promise has not completed when console.log($scope.servers); runs.
You should still handle the promise in your controller (until you move to using your router's resolve but one step at a time).
Here's how you'd change your code:
cbApp.controller('serversCtrl', function($scope, serversService){
serversService.getServers().success(function(servers) {
$scope.servers = servers;
});
});
cbApp.service('serversService', function($http){
this.getServers = function(){
return $http.get(BASE_URL + '/api/s');
}
});
I've been trying to get my angular js page to work with indexeddb, and I'm trying to do it right. So far it's going smoothly but I've really been struggling getting my promises to work as I expect in regards to my data loading. I followed the advice of this other question and I think I understand what it's trying to do, but I can't get it to work. I think the issue is that it is using the routeProvider which expects ajax requests and I'm not doing that, it's all client side. I am using the angular-indexedDB pluging that can be found on GitHub here. These are the relevant bits of what I'm doing.
angular.module('characterApp',['ngRoute','xc.indexedDB'])
.constant('dbName', 'character')
.constant('storeName', 'character')
.constant('version', 1)
.constant('emptyCharacter', {})
.value('jsPlumbInstance', {})
.config(function($indexedDBProvider, dbName, storeName, version) {
$indexedDBProvider.connection(dbName)
.upgradeDatabase(version, function(event, db, tx){
db.createObjectStore(storeName, {keyPath: 'guid'});
});
})
.config(function($routeProvider){
console.log('Configuring route');
$routeProvider
.when('/js/angular/controllers/characterController.js', {
controller:'characterController',
resolve:{
'characterData':function(DataService){
console.log('resolving promise');
return DataService.promise;
}
}
})
})
.service('DataService', ['$indexedDB', 'storeName', 'emptyCharacter', function($indexedDB, storeName, newObject){
var objects = [];
var index = 0;
var objectStore = $indexedDB.objectStore(storeName);
var promise = objectStore.getAll().then(function(results) {
objects = results;
console.log("DB Objects loaded.");
});
console.log("Promise created");
function getControllerObject(propertyName){
return objects;
}
return {
getControllerObject : getControllerObject,
promise : promise
};
}])
.controller('characterController', ['$scope', 'DataService', function($scope, DataService) {
console.log('Promise is now resolved: ' + DataService.getControllerObject()
);
}]);
When I run it my console outputs the following:
Configuring route
characterApp.js:52 Promise created
characterController.js:2 Promise is now resolved:
characterApp.js:50 DB Objects loaded.
However if I understand the other answer mentioned above, the output should be:
Configuring route
characterApp.js:52 Promise created
characterApp.js:50 DB Objects loaded.
characterController.js:2 Promise is now resolved:
If it helps, my full code is on GitHub here, but you will need node.js to run the custom server.js file I have in the /www folder for all the content to load properly. You could get it to work with minimal effort elsewhere if you moved the content from the www/pages directory into their placeholders on the index.html though. Or infact, you could remove the nonstandard tags alltogether, I think it would still work. I suspect all of that is unnecessary and I just don't understand how these things work. I'm fairly new to angular but trying to learn how to do things the right way.
angular.module('characterApp',['ngRoute','xc.indexedDB'])
.constant('dbName', 'character')
.constant('storeName', 'character')
.constant('version', 1)
.constant('emptyCharacter', {})
.config(function($indexedDBProvider, dbName, storeName, version) {
$indexedDBProvider.connection(dbName)
.upgradeDatabase(version, function(event, db, tx){
db.createObjectStore(storeName, {keyPath: 'guid'});
});
})
.service('DataService', ['$indexedDB', 'storeName', 'emptyCharacter', function($indexedDB, storeName, newObject){
var objects = [];
var index = 0;
var objectStore = $indexedDB.objectStore(storeName);
var promise = objectStore.getAll()
console.log("Promise created");
function getControllerObject(propertyName){
return objects;
}
return {
getControllerObject : getControllerObject,
promise : promise
};
}])
.controller('characterController', ['$scope', 'DataService', function($scope, DataService) {
var characters = [];
DataService.promise.then(function(results){
characters = results;
$scope.character = characters[0];
console.log("DB Objects loaded.");
});
);
}]);
I didn't need the routeprovider at all, I just was doing stupid things with my promises.
I have the following controller in my application, but there is some strange behaviour that I cannot explain. I've numbered two of the lines to help with the description, they don't both exist at the same time in the live code.
var app = angular.module('movieListings', ['ngResource', 'ngRoute', 'ui.bootstrap', 'ng']);
var cachedMovieList = [];
//Controller for movie list
app.controller('MovieListController', ['$http', function($http){
var mlc = this; //needed for the $http request
this.movies = cachedMovieList;
this.loaded = false;
this.error = false;
if(this.movies.length == 0) {
console.log("Grabbing new movie list from DB");
$http.get('data/movies.json').success(function(data){
mlc.movies = data;
mlc.loaded = true;
cachedMovieList = data; //(1)
}).error(function(data){
mlc.error = true;
});
cachedMovieList = this.movies; //(2)
} else {
this.loaded = true;
}
}]);
With the code as above with line (1) present and line (2) not present, I am able to cache the result so that when I flick between pages I don't need to constantly re-get the data.
However if I remove line (1) and insert line (2), the variable "cachedMovieList" is never populated. I would expect it to be based on the fact that "mlc.movies" was assigned to... but I cannot understand why this is the case?
Any advice welcome.
Implement a factory that retrieves the data. Use angular.copy to preserve the array reference when the data returns from the $http call.
var app = angular.module('movieListings', ['ngResource', 'ngRoute', 'ui.bootstrap', 'ng']);
app.factory('movies', function($http) {
var movies = {
data: [],
loaded: false,
error: false
};
$http.get('data/movies.json').success(function(data){
angular.copy(data, movies.data);
movies.loaded = true;
}).error(function(data){
movies.error = true;
});
return movies;
});
Inject the factory into your controller:
//Controller for movie list
app.controller('MovieListController', ['$scope','movies', function($scope, movies){
this.movies = movies;
}]);
Factories (like services) are singletons. They are initialized once, and cached for the entire lifetime of the SPA.
Use the controller in the view:
<div ng-controller="MovieListController as ctrl">
<div ng-show="!ctrl.movies.loaded"> Loading... </div>
<ul>
<li ng-repeat="movie in ctrl.movies.data">
{{ movie.name }}
</li>
</ul>
</div>
If I've understood this correct, you're entering the if condition only when this.movies.length == 0. In such a case, this.movies will be null, so cachedMovieList would get populated with a null value.
Because (2) probably gets executed first before the $http.get() request is finished. $http.get() is an AJAX request.
If you want to cache, you might want to use $cacheFactory instead :)
I believe you are mistaking the live updation of values that happens in view to live updation that would happen with variable assignments. Your line 2 will set cachedMovieList to [] initially. I believe that is quite obvious. But you think that since callback updates this.movies that change would cascade to cachedMovieList. That won't happen as you are re-assigning the mlc.movies variable that means it refer to new variable instead of modifying existing value.
If you really want to make you logic work, please update mlc.movies variables like following
mlc.length = 0 // Empty the array
mlc.push.apply(mlc, data);
Please check following answer for more information
How do I empty an array in JavaScript?