I'm having a problem loading a record from firebase into my view when directly linking to the intended route with the key as a routeParam. As shown below in my routeProvider I've specified the param later called in the SpecController. The problem is, if I directly type the url in or click an offsite link the model bindings are all "undefined" indicating that the record is not loaded.
// Snippet from RouteProvider
.when('/spec/:urlKey', {
templateUrl: 'views/spec.html',
controller: 'SpecController',
controllerAs: 'spec'
})
// Snippet from SpecController
var cKey = $routeParams.urlKey;
this.check = this.checkList.$getRecord(cKey);
After a bit of research it seems I should call a resolve in the routeprovider and run that second bit of code. Though I'm not sure if that's the problem or if it has to do with the way angular loads itself and the routeparams as well as the order thereof.
Just as a side note it is fully functional when I load the application from a separate route/view and then click a link within the application which then uses $location to set the url and param as shown below.
// Snippet from ListController
this.viewCheck = function(check){
var ref = this.checkList.$keyAt(check);
$location.path('/spec/'+ref);
};
The "key" I'm referring to as well as all other additional functions I'm using and referring to can be found directly at the following section of the Firebase API Guide: https://www.firebase.com/docs/web/libraries/angular/guide.html#section-arrays
I can't really reproduce the issue in a fiddle because the only way it happens is if you directly place the link in the url of a browser. I've made a small video showing the problem. When the video opens you see the result of entering the url directly, then by simply clicking "Home" and then "Back" it then loads appropriately. http://screencast.com/t/4OKRTVnc
As mentioned in the comments, you should use the Angular route resolution process based on promises. Here is a working plunkr demonstration, but the highlights are:
Build a Data Service that Returns Angularfire's Promises
There are many, many ways to structure and access your Firebase data, but the important thing here is to use the promises returned by Angularfire. This keeps you from making duplicate sync objects for the same data, and allows you to play nice with Angular.
testApp.factory("ChatDataService", ["$firebase",
function ($firebase) {
var rootRef = new Firebase("https://docs-examples.firebaseio.com/");
var chatDataService = {};
chatDataService.getChatRooms = function () {
if (!chatDataService.chatRoomsPromise) {
var chatRoomRef = rootRef.child("web/data/rooms");
var chatRooms = $firebase(chatRoomRef).$asArray();
chatDataService.chatRoomsPromise = chatRooms.$loaded();
}
return chatDataService.chatRoomsPromise;
};
chatDataService.getRoom = function (roomId) {
return chatDataService.getChatRooms()
.then(function (chatRooms) {
return chatRooms.$getRecord(roomId);
});
};
chatDataService.getRoomMessages = function (roomId) {
if (!chatDataService.messages || !chatDataService.messages[roomId]) {
chatDataService.messages = chatDataService.messages || {};
var roomMessagesRef = rootRef.child("web/data/messages").child(roomId);
var roomMessages = $firebase(roomMessagesRef).$asArray();
chatDataService.messages[roomId] = roomMessages.$loaded();
}
return chatDataService.messages[roomId];
};
return chatDataService;
}
]);
Return Promises From Resolve Functions
You can write a small route resolution function that uses your data service to get the correct data. Make sure you return a promise.
when("/room/:roomId", {
controller: "RoomController",
resolve: {
room: ["$route", "ChatDataService", function ($route, chatDataService) {
var roomId = $route.current.params.roomId;
return chatDataService.getRoom(roomId);
}],
messages: ["$route", "ChatDataService", function ($route, chatDataService) {
var roomId = $route.current.params.roomId;
return chatDataService.getRoomMessages(roomId);
}]
},
templateUrl: "roomView.html"
})
Keep Your Controllers Dumb
You could have done all the Firebase lookup and promise resolving in each controller. In this case, I kept the controllers dumb by letting Angular routing wait on promise resolution.
testApp.controller("RoomController", ["$scope", "$firebase", "room", "messages",
function ($scope, $firebase, room, messages) {
$scope.room = room;
$scope.messages = messages;
}
]);
Related
I'm creating a new multi-use website for a new brand my company is launching in a few weeks. We use a WordPress backend and via the WP REST API, are now able to uncouple the system and use NodeJS/Express/AngularJS for our front end and middleware applications.
Currently, when I load the landing page, an HTTP GET Request is made to WordPress for all of the relevant posts for our front page. This data is then passed to a service to be used across controllers.
So, the initial set up is this:
landingController
angular
.module('glossy')
.controller('LandingController', LandingController)
LandingController.$inject = ['featuredService', 'sharedPostsService'];
function LandingController(featuredService, sharedPostsService){
// Set up view model (vm) variables
var vm = this;
vm.featured = [];
// Call this function on state 'home' load
activate();
// Calls getFeatured function and prints to console
function activate(){
return getFeatured()
.then(function(){
console.log('GET Featured Posts');
});
}
// Calls the featuredService then stores response clientside for rendering
function getFeatured(){
return featuredService.getFeatured()
.then(function(data){
vm.featured = data;
sharedPostsService.setPosts(data);
return vm.featured;
});
}
}
Factory for HTTP Request
angular
.module('glossy')
.factory('featuredService', featuredService)
featuredService.$inject = ['$http'];
function featuredService($http){
return {
getFeatured: getFeatured
};
// Performs HTTP request then calls success or error functions
function getFeatured(){
return $http.get('/api/posts')
.then(getFeaturedComplete)
.catch(getFeaturedFailed);
// Returns response data
function getFeaturedComplete(response){
return response.data;
}
// Prints error to console
function getFeaturedFailed(error) {
console.log('HTTP Request Failed for getFeatured: ' + error.data);
}
}
}
Service that holds data from factory
angular
.module('glossy')
.factory('sharedPostsService', sharedPostsService)
function sharedPostsService(){
var listPosts = [];
return {
setPosts: function(posts){
listPosts = posts;
},
getPosts: function(){
return listPosts;
}
};
}
Now, when a user clicks on a post on the landing page, she is taken to a page that displays on the article that she clicked on, which works. However, if she refreshes this page, all the data is gone. Calling the service results in an empty object.
Post controller
angular
.module('glossy')
.controller('PostController', PostController)
PostController.$inject = ['$window', '$filter', '$stateParams', 'sharedPostsService'];
function PostController($window, $filter, $stateParams, sharedPostsService){
var vm = this;
vm.postsList = sharedPostsService.getPosts();
vm.postTitle = $stateParams.title;
vm.thisPost = filterPosts();
function filterPosts() {
return $filter('filter')(vm.postsList, vm.postTitle);
};
}
How do I set this up to ensure that the data persists through refresh? I looked into using localStorage but everything I found said it involved stringifying data and storing it in key value pairs?
Any help is appreciated.
You cannot use a service to persist data on a page refresh.
If the data is large use a database, else use sessionStorage or localStorage.
Storing the data:
window.localStorage['data'] = JSON.stringify(data);
Retrieving the data:
return angular.fromJson(window.localStorage['data']);
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'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.
In my AngularJS controller I'm trying to do something relatively simple: I'm trying to populate a <select> element dynamically in the controller. To do so I need to wait for my localized UI text data to be loaded and data from my server to be loaded and this is causing a problem for me.
What my HTML Looks like:
<select
data-ng-model="group"
data-ng-options="options.value as options.label for options in userGroups">
<option>--</option>
</select>
Then my controller is actually implementing a base controller "class" which allows me to share logic between controllers:
// exampleController.js
myModule.controller('exampleController',
['$scope', '$timeout', '$routeParams', '$controller',
function ($scope, $timeout, $routeParams, $controller) {
// Instantiate the base controller class and set it's scope
// to this controller's scope. This is how the base and child
// controllers will share data and communicate.
var base = $controller('baseController', { $scope: $scope });
}]);
And here is a relevant snippet of the baseController:
// baseController.js
$scope.getDataFromUrl = function (url, cache, successFunction) {
$http.get(url, { cache: cache })
.success(function (data) {
if (!handleErrorInData(data))
{
successFunction(data);
}
});
};
$scope.getDataFromUrl(uiTextResourceUrl, true, function (data) {
$scope.uiText = data;
});
So baseController fetches the text resources when it loads and sets it to the scope when it's finished retrieving the data. exampleController on the other hand will fetch other data from the server via the getDataFromUrl() function defined in baseController like so:
$scope.getDataFromUrl(dataUrl, false, function (data) {
// Do stuff with the returned data...
};
My issue is coming from this part of the exampleController code where I populate the data of the <select> element from earlier:
// exampleController.js (Continued...)
$scope.getDataFromUrl(userGroupsUrl, false, function (data) {
initSelectDropdown(data);
});
var initSelectDropdown = function (data) {
var userGroups = [];
// Parse data retrieved from the server and populate the <select> bound data
// array with it
var index;
for (index = 0; index < data.length; ++index)
{
var newGroup = {
value: data[index],
label: data[index]
};
// One of the data entries will have a value of "", this group needs its
// label to be set to the localized string "No Group"
if (newGroup.value === "")
{
newGroup.label = '<' + $scope.uiText['NoGroup.Text'] + '>';
}
userGroups.push(newGroup);
}
// Set local userGroups to scope
$scope.userGroups = userGroups;
};
The problem I'm having is here in the initSelectDropdown() function. I need to have both the data from the server and the uiText resource data from the server, particularly the line newGroup.label = '<' + $scope.uiText['NoGroup.Text'] + '>'; where the data is being transformed in a way that is dependant on localized resources being loaded. I researched the issue and saw that using $q.all() might be a solution but unfortunately in my case there is no way for me to call $q.all() because the two calls to fetch data are being made from different functions in different controllers (data being requested from child controller and resources being requested from base controller).
In the view it's easy to fix this because if I bind an element to $scope.uiText['SomeText.Text'] then it doesn't care if SomeText.Text is undefined at first and when it is eventually populated the UI will automatically pick up on the change.
How can I make this work? Is it possible to achieve something like how binding works in the view?
For sharing code angular provides services/factory, you don't need to use base controller.
Define a factory class and add two methods, one to fetch your server data and other to fetch uiText data. these methods will return promises.
Now in your controller you can use $q.all() passing the two promises that will be resolved when ajax call is complete.
Hope it makes sense ?
I have a resource factory that builds objects for accessing our API. I use an environment variable to determine the base part of the URL - whether or not to include 'account/id' path segments when the admin user is 'engaging' a client account.
The sessionStorage item that holds the 'engagedAsId' doesn't get read, though for instances created after engaging an account. It requires a full reload of the app to pick up that change. Here is the factory code:
myapp.factory('ResourceSvcFactory',
['$rootScope', '$resource',
function ($rootScope, $resource) {
function ResourceSvcFactory (endpoint) {
// vvv problem is here vvv
var accountId = sessionStorage.getItem('engagedAsId');
var apiPath = (accountId != null)
? '/api/account/' + accountId + endpoint
: '/api' + endpoint;
var Resource = $resource(apiPath+':id/',{
// default params
id:''
},{
// custom actions
update: {method: 'PUT'}
});
return Resource;
}
return ResourceSvcFactory;
}]);
myapp.factory('AssetsResource', ['ResourceSvcFactory', function (ResourceSvcFactory) {
var endpoint = '/assets/';
var Resource = ResourceSvcFactory(endpoint);
return Resource;
}]);
I implement this in my Controller like this:
myapp.controller('AssetGroupListCtrl', [ 'AssetgroupsResource', function (AssetgroupsResource) {
var AssetGroups = AssetgroupsResource;
// ... rest of controller
}]);
When i run this it works fine. But, if i change the engaged status in the sessionStorage without a full reload, the instance in the controller does not pick up the new path.
Is there a way to 'refresh' the instance? ...automatically?
After hours of research, it appears that the fundamental flaw in what I'm trying to do in the question is this: I'm trying to use a 'singleton' as a 'class'. from the docs:
Note: All services in Angular are singletons. That means that the injector uses each recipe at most once to create the object. The injector then caches the reference for all future needs.
http://docs.angularjs.org/guide/providers
My work around was to create the $resource inside a method of a returned object. Here is an example:
MyApp.factory('AssetgroupsResource',
['$rootScope', '$resource',
function ($rootScope, $resource) {
return {
init: function () {
var accountId = sessionStorage.getItem('engagedAsId');
var apiPath = (accountId != null)
? '/api/account/' + accountId + endpoint
: '/api' + endpoint;
// default params
id:''
},{
// custom actions
});
return Resource;
}
}
}]);
This made it possible to build the object at the right time in the controller:
MyApp.controller('AssetGroupListCtrl', ['Assetgroups', function (Assetgroups) {
var Assetgroups = AssetgroupsResource.init();
// now I can use angular's $resource interface
}]);
Hope this helps someone. (or you'll tell me how this all could've been done in 3 lines!)
You can always call $scope.$apply(); to force an angular tick.
See a nice tutorial here: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
I think $resource uses promise which might be an issue depending on how you implement your factory in your controller.
$scope.$apply() can return an error if misused. A better way to make sure angular ticks is $rootScope.$$phase || $rootScope.$apply();.