I am using super heroic Angularjs in my application. I have a couple of pages like home.html, project.html, map.html. Each pages has a controller associated with it e.g. HomeCtrl, ProjectCtrl, MapCtrl. In my home.html user can create a project or navigate to project.html. In project.html I have list of all projects. When user clicks on a project he is navigated to map.html where I have some information regarding to project. I am using ngRoute for routing between the views. I am facing some challenges to share data across the controllers. I have created a service called dataFactory which stores all the data retrieved from backend. In my project.html view, I load all the data from backend and store them in service. When user lands into a project I use data stored in the dataFactory. The concern is that when user refreshes the page when he is on the map.html, all the data which are stored in dataFactory are wiped out and not loaded back cause data loading happens in the project.html page. I don't know how can I deal with it. I can not make a call to backend in every controller to get the data. I am planning to load the common data in app.run() method. But in that case I have to broadcast/emit the events to notify controllers, which will also be messier and will eventually lead to errors cause I know my application is going to be a huge application.
There is a solution but it needs some additional configuration while making routes in your $routeProvider, You can resolve your route when you have your data fetch from the backend. By using this method if a user refreshes the page on one of your project it will receive the data first then display that particular page.
First you have to modify your dataFactory something like this
app.service('MyService', function($http) {
var myData = null;
var promise = promise || $http.get('data.json').success(function (data) {
myData = data;
});
return {
promise:promise,
doStuff: function () {
return myData
}
};
});
Then in your $routeProvider you could make route to resolve when your data is fetched (that is receives its promise) more over by using this method it wont make another data call if your data is stored.
app.config(function($routeProvider){
$routeProvider
.when('/',{controller:'MainCtrl',
template:'<div>From MyService:<pre>{{data | json}}</pre></div>',
resolve:{
'MyServiceData':function(MyService){
return MyService.promise;
}
}})
.when('/b',{controller:'MainCtrl2',
template:'<div>From MyServic2e:<pre>{{data | json}}</pre></div>',
resolve:{
'MyServiceData':function(MyService){
return MyService.promise;
}
}})
})
I've a made a working Plunker for demo. Fell free to ask any question regarding this.
Hope it helps.
when you refersh the page, the app module loads again wiping out all the stored vars. You can use sessionStorage or localStorage to maintain data.
When you store your data into service/ factory store it in to your browser's local storage too. So, when user refresh the page, you can check whether your local storage has the data or not. If there is data in your local storage just save these data into your service/ factory.
That's all !!!
If you are struggle to implement these things please update me, I can help you on the code also.
Related
As we work in angular when we route from one url to another then controller data is Rest but service data is not reset.
Can someone please explain why its not reset. Any help is appreciated.
Thanks
Services are only instantiated once and every component depending on the service gets the same shared instance of it. Services are not "reset"/destroyed/torn down, they're permanent. Controllers are bound to scopes and come and go with the scope.
This in fact allows you to have a constant "backend" in the form of services which retain their state throughout the entire life cycle of the app, while controllers are temporary things bound to views which come and go as the GUI changes.
Angular services are:
Lazily instantiated – Angular only instantiates a service when an
application component depends on it.
Singletons – Each component
dependent on a service gets a reference to the single instance
generated by the service factory.
You can read more about it in Angular's documentation: https://docs.angularjs.org/guide/services.
This issue was a bit old but let me share on how I did to delete my data stored in service.
service.ts
data: any;//I made a storage variable like this so it will be undefined value by default
removeProductData() {
this.data= undefined;
}
//In your component just call this function `removeData()` wherever you want to delete your data.
EDIT
The short version:
Say I have application data is many different services. How do I get around needing to inject all of those services into every controller that displays application state?
EDIT
I am building my first Angular application. The basic design is I have a home page that shows the value of about 5 different variables (which are each pretty complicated). While on this page the app is collecting and analyzing data from bluetooth. Occasionally, the these 5 variables and some bluetooth data are saved to a REST back end and also saved to the device. There are pages for each of these 5 variables to change their value.
I have done my best to follow best practices. I have very thin controllers. I use services for all my data. I really only use $scope for binding data between views and controllers.
My issue now is that I started with a global "State" service to keep track of those 5 variables. I inject into any controller that needs to display state, and bind the html to it. Any time I want to change any state, I call a method of that State service to do it. This worked well, but now that State service is getting huge.
I have tried to break functions out to other services, but I run into the issue of needing to read data from the State service, then writing back to other properties of the State service. If I inject the other service into State, I can't inject State into the other service too.
I have thought about how I could have many smaller services, but I keep coming back to when I save the data to the server. When I do that I need to gather up data from every corner of the application to send up. If all this information is stored in different services, I am left with injecting all of them into a single service once again.
As I write this, I am pretty sure I am missing a big concept with using $scope across an application.
Any pointers would be appreciated,
Thanks,
Scott
Could you divide things into sub-services, and then make the State service an aggregator for these sub-services, then instead of injecting State into the sub-services, you inject the specific sub-service that you need? E.g.:
var app = angular.module('services', []);
app.service('sub1', function(){
return {
// ...
}
});
app.service('sub2', function(sub1){
var data = sub1.getData();
data.prop = 'new_value';
sub1.setData(data);
return {
// ...
}
});
app.service('State', function(sub1, sub2){
var data = sub1.getData();
data.prop = 'new_value';
sub1.setData(data);
var data = sub2.getData();
data.prop = 'new_value';
sub2.setData(data);
return {
// ...
}
});
Looks like you need Redux to help you manage your application state
https://github.com/wbuchwalter/ng-redux
In my AngularJS application, I have a Session service object that contains stuff like the current user, their preferences, the current company they belong to, and the current theme that they are using. Many places in my application refer to the Session service when they need to get at this data.
Because these variables are in a service, I cannot use scope watches to detect changes. So instead, I've decided to use the observer pattern. Various places in the application, such as other services, directives, controllers, etc. will register themselves with the Session service and provide a callback to be executed whenever the Session changes.
For example, if the user changes their theme, the <style> element in index.html that uses a custom directive will be notified, and it will recreate all of the overriding css rules for the new colors.
For another example, whenever the user's avatar is updated, the main menu bar controller will be notified to refresh and redraw the avatar. Stuff like this.
Obviously the data in Session has to be refreshed at least once before the various controllers, directives, etc. use it. The natural place to ask the Session service to get its session data was in a run block for the application-level module. This works pretty well, but I don't think it's the best place either.
One problem I have noticed is that when Firebug is open, the asynchronous nature of things loading causes ordering issues. For example, the directive that runs on the <style> element will run AFTER the Session service has refreshed in the application's run block... which means the theme will not get updated after pressing F5 because the callback is registered after the initialization of the data occured. I would have to call a manual refresh here to keep it in sync, but if I did that, it may execute twice in the times where the order is different! This is a big problem. I don't think this issue is just related to Firebug... it could happen under any circumstance, but Firebug seems to cause it somewhat consistently, and this is bad.
To recap... This asynchronous ordering is good:
Theme Directive registers callback to Session
Menu Bar application controller registers callback to Session
Session.refresh() is called in .run block.
This asynchronous ordering is bad:
Menu Bar application controller registers callback to Session
Session.refresh() is called in .run block.
Theme Directive registers callback to Session, but callback does not get executed since Session.refresh() was already executed.
So rather than use the observer pattern, or refresh the Session state via a run block, what the best way to design the services, etc. so that the session data will ALWAYS get refreshed after (or maybe before) the various other parts of the application require it? Is there some kind of event I can hook into that gets executed before directives and controllers are executed instead of the run block?
If my approach is generally sound, what can I add to it to really make it work the way it should?
Thanks!
In angular.js you have 2 way of using global variables:
use a $rootScope
use a service
Using $rootScope is very easy as you can simply inject it into any controller and change values in this scope. All global variables have problems!
Services is a singletons(What you need)!
I think in your case you can use
$rootScope
And
$scope.$watch
Great answer
Is there a reason you can't access the variables directly like this:
app.factory('SessionService', function() {
var items = {
"avatar": "some url"
};
return items;
});
var MainController = [$scope, 'SessionService', function($scope, SessionService){
$scope.session = SessionService;
$scope.modifyAvatar = function(url){
$scope.session.avatar = "some new url";
};
}];
var HeaderController = [$scope, 'SessionService', function($scope, SessionService){
$scope.session = SessionService;
// You probably wouldn't do this, you would just bind
// to {{session.avatar}} in your template
$scope.getAvatar = function(){
return $scope.session.avatar;
};
}];
I'm developing an AJAX-heavy application with AngularJS and need requests to not be re-made when the user clicks the back button on their browser. For example a set of data takes 2-3 seconds to load and then if the user navigates to another page and then clicks back the data has to be reloaded. Is there a way to prevent this - or alternatively a different way to design my app such that data persists through a session?
If you're using ngResource for loading data from api then set the cache to true in actions as in described in documentation
cache – {boolean|Cache} – If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching.
https://docs.angularjs.org/api/ngResource/service/$resource
Example:
this.service=$resource('www.example.com/api/v/stats',
{
callback: "JSON_CALLBACK"
}, {'foo': {'method': 'GET', 'cache': true}}
);
Loading data through this.service.foo() will cache the request and on back button, it will use the cached data instead of reloading it.
I strongly suggest that you study more on the usage of routing with AngularJS
A nice and quick way to do so would be watching some of John's tutorials, starting with this one: https://egghead.io/lessons/angularjs-ng-view
Finally, what you are trying to accomplish is showed in this one: https://egghead.io/lessons/angularjs-route-life-cycle
Hope this helps.
In an app I'm currently developing, I use the $routeProvider heavily for each of the modules.
I do something like:
$routeProvider.when(/someModule/page1Condition1, {templateUrl: 'page1.tpl.html', controller: 'page1Ctrl'});
$routeProvider.when(/someModule/page1Condition2, {templateUrl: 'page1.tpl.html', controller: 'page1Ctrl'});
Then, in the controller for page1 I do something like:
if($location.path()==='/someModule/page1Condition2){
// something that should be done only when Condition2 is true,
// for example, loading data using ajax
$http.get('somePath')
.success(function(data){
$scope.myData = angular.fromJson(data);
});
}
In this way, I have just one controller but conditionally fetch data using the url path as an information source. Think of it like something that wants to be as close as REST as possible, but is actually not REST.
It's important to mention that I also have several weird requirements imposed by my client, thus this is quite probably not the best way to solve this problem (it could even be an antipattern, although I like to think that is just a temporary hack).
I have a Rails application which uses AngularJS on the front-end. I also have a route in the format "/api/:user_id/submissions/:id" to access specific submissions from a user. On the front-end I'd like to display each post from the Devise user that is currently logged in, and only their posts. I have created both an Angular factory:
var brainDB = angular.module('brainDB',['ngResource']).factory('userSubmission', function($resource){
var service = $resource('/api/:user_id/submissions/:id', {user_id: '#user'}, {id: '#id'} );
return service;
And have it scoped to my controller:
brainDB.controller('SubmissionsCtrl',['$scope', 'Submission', 'userSubmission',
function($scope, Submission, userSubmission){
$scope.submissions = Submission.query();
$scope.userSubmissions = userSubmission.query();
}]);
The only problem is that the factory at the top doesn't work. I can output every single submission in my database, but I don't know how to tell Angular what the user_id of the current_user is. I have a submissions.rb controller with an action which successfully pulls all of the posts for the specific user from my route, "/api/:user_id/submissions/" but like I said I don't know how to tell Angular what the current_user.id is because current_user can only be accessed from Rails.
I've been trying to solve this for a week now and haven't found much help through Google searches. Any advice is greatly appreciated.
My own app has another server endpoint call defaults & angular service Metadata that gets initialized in an angular .run() block. This block pulls a currentUser object back (with other metadata) to initialize $rootScope variables. From there, I can call other angular services with: userSubmission.query({user_id: $rootScope.currentUser.id}); etc. in my angular controllers.
Another option would be to generate metadata content in a javascript file with all your metadata (i.e. metadata.js.erb in which you let rails populate variables (using <%= =>) that are available to your whole angular app.
Hope that helps.