Retrieving Data from AngularFire - javascript

I'm trying to retrieve data from Angularfire using a service, and then setting the returned value to my scope in my controller.
When I run the code below, I get undefined back for scope.sessions.
SERVICE:
app.factory('sessions', function(){
var refToSessions = new Firebase('myFireBaseURL');
var allSessions = [];
return {
getSessions: function () {
refToSessions.on("value", function (sessions) {
allSessions.push(sessions.val());
return allSessions;
});
}
};
});
CONTROLLER:
app.controller('SessionsCtrl', ['$scope', '$state', 'Auth', 'sessions', function($scope, $state, Auth, sessions){
$scope.sessions = sessions.getSessions();
$scope.submitSession = function() {
console.log($scope.sessions);
}
});

You're trying to return asynchronous data.
You are logging allSessions to the console before the data has downloaded from Firebase.
Use $firebaseArray from AngularFire.
app.constant('FirebaseUrl', '<my-firebase-url>');
app.service('rootRef', ['FirebaseUrl', Firebase);
app.factory('Sessions', function(rootRef, $firebaseArray){
var refToSessions = ref.child('sessions');
return $firebaseArray('sessions');
}
Then injection Sessions into your controller:
app.controller('SessionsCtrl', function($scope, $state, Auth, Sessions){
$scope.sessions = Sessions; // starts downloading the data
console.log($scope.sessions); // still empty
$scope.submitSession = function() {
// likely by the time you click here it will be downloaded
console.log($scope.sessions);
$scope.sessions.$add({ title: 'new session' });
};
});
The data starts downloading once it's injected into your controller. When it's downloaded, $firebaseArray knows to trigger $digest, so it appears on the page.
Since you're using ui-router, you can use resolve to make sure the data exists before injecting it into your controller:
app.config(function ($stateProvider) {
$stateProvider
.state("session", {
controller: "SessionsCtrl",
templateUrl: "views/sessions.html",
resolve: {
sessions: function(Sessions) {
// return a promise that will fulfill the data
return Sessions.$loaded();
}
}
})
});
Now you would change your controller code to this:
app.controller('SessionsCtrl', function($scope, $state, Auth, sessions){
$scope.sessions = sessions; // data is available since injected by router
console.log($scope.sessions); // logs the appropriate data
$scope.submitSession = function() {
$scope.sessions.$add({ title: 'new session' });
};
});

Related

Is it possible to pass param from state to state with angularJs?

I wish to pass a param from one store-state to the display product info in products-state:
My app - storeApp
.config(['$stateProvider', function($stateProvider) {
$stateProvider
.state('store', {
url: '/store',
templateUrl: 'store/store',
controller: 'storeCtrl'
})
.state('products', {
url: '/products/:productSku',
templateUrl: 'store/product',
controller: 'productCtrl',
resolve: {
productResource: 'productFactory',
_product: function(productResource, $stateParams){
return productResource.getProduct($stateParams.productSku);
}
}
Store.jade
a(href='/products/{{product.sku}}')
Product controller
.controller("productCtrl", function ($rootScope, $http, $stateParams, productFactory, storeFactory) {
//.controller('productCtrl', ['_product', function ($scope, $rootScope, storeFactory, _product) {
console.log($stateParams.productSku);
Product Factory
function getProduct(sku) {
return $http.get('http://localhost:3000/api/products/' + sku );
}
Since I am using MEAN Stack, node has the router attached to express:
Server.js
const storeController = require('./controllers/store');
server.get('/store/product', passportConfig.isAuthenticated, storeController.getProductPage);
Store.js
exports.getProductPage = (req, res) => {
res.render('store/product', {
title: 'PP',
angularApp: 'storeApp'
})
}
I tried returning _product but I get Unknown provider: _productProvider <- _product <- productCtrl
I tried using ui-sref - a(ui-sref="products({productSku:'{{product.sku}}'})") in store.jade to send param from store_State to products_State & finally got an object back from API.
Now the issue is that node will not return the view.
Basically what I am trying to achieve is:
Node serving client views, all store views - store/ product/ cart are attached to angular app served through Server.js, Clicking store product will redirect to product page after resolve product info from api.
I am getting product info but not getting product view.
I looked it up but all solutions did not work....maybe my bad :-(
How can I go about this?
UPDATE-1: this is whats happening:
UPDATE-2:
When I pass the control to angular, I have express routing the menu, and angular stateProvider routing/ connecting views to controllers.
Main view that loads is the store itself:
app.js - store route
$stateProvider
.state('store', {
url: '/store',
templateUrl: 'store/store',
controller: 'storeCtrl'
})
server.js (express)
server.get('/store', passportConfig.isAuthenticated, storeController.getStorePage);
store.js
exports.getStorePage = (req, res) => {
res.render('store/store', {
title: 'S--tore',
angularApp: 'storeApp'
});
}
store.ctr.js
angular.module("storeApp")
.controller("storeCtrl", function($rootScope, $http, storeFactory) {
var products;
storeFactory.getProducts().then(function(_products) {
products = _products.data;
$rootScope.products = products;
});
That loads just fine!
But when I try to send the param productSku from store view to product view and have the resolve send product params back to product view that where it stops working, it's either I get the view OR i get the params.
I tried different ways of resolve, they all result the same - view OR product params.
app.js - product route
.state('products', {
url: '/products/:productSku',
templateUrl: 'store/product',
controller: 'productCtrl',
resolve: {
_product: function ($stateParams, $state, $http) {
return $http.get('http://localhost:3000/api/products/' + $stateParams.productSku );
//return productResource.getProduct($stateParams.productSku)
}
}
})
If I remove the resolve and send a(href='/products/{{product.sku}}') from store.jade I get the template in the route, chrome console error I get is `Error: $injector:unpr Unknown Provider _product <- productCtrl
product.ctr.js
.controller('productCtrl', ['_product', function ($rootScope, $http, $stateParams, productFactory, storeFactory, _product) {
If I send a(ui-sref="products({productSku: product.sku })") with resolve I get product params (shown in WebStorem snapshot above) NO view.
angular will not load jade templates, You will need an html template, The jade template is loaded by express. You might like to try using ui-view like this:
Store.jade
div(ui-view)
a(href='/products/{{product.sku}}')
Which should make angular look for the unnamed view when loading the route.
Your templateUrl's don't look to be pointing to files, perhaps you're missing the file extension?
Make sure you return a $promise in resolve as ui-router waits until they are resolved before rendering the view.
I'd recommend having named views with corresponding config in route too:
.state('store', {
url: '/store',
views: {
'#': {
templateUrl: 'store/store.html',
controller: 'storeCtrl'
}
}
})
.state('products', {
url: '/products/:productSku',
templateUrl: 'store/product',
controller: 'productCtrl',
resolve: {
_product: function ($stateParams, $state, $http) {
return $http.get('http://localhost:3000/api/products/' + $stateParams.productSku ).$promise;
}
}
})
See the docs here: https://github.com/angular-ui/ui-router/wiki/Multiple-Named-Views
This is the solution I found:
store.jade
a(href='/products/{{product.sku}}' ng-click='sku(product.sku)')
stroe.ctr.js
$rootScope.sku = function(value){
storeFactory.singleProduct.productSku = value;
storeFactory.singleProduct.saveSku();
}
store.fac.js
var singleProduct = {
productSku : '',
saveSku: function() {
sessionStorage.productSku = angular.toJson(singleProduct.productSku);
},
getSku: function() {
singleProduct.productSku = angular.fromJson(sessionStorage.productSku);
return singleProduct.productSku;
}
}
product.ctr.js
var sp = storeFactory.singleProduct.getSku();
productFactory.getProduct(sp).then(function (product) {
$rootScope.product = product.data;
});
product.fac.js
function getProduct(sku) {
return $http.get('http://localhost:3000/api/products/' + sku );
}
Basically I am storing productSku to sessionStorage and getting it back from there when product.jade view loads...
Thanx to all who tried...
You can pass it as $state.data in your controller.
toState = $state.get("some-state");
toState.data.foo = $scope.foo;
$state.go(toState);
You have not included dependancy of _products in storeCtrl. When you call that service you get an error.
Correct code is:
angular.module("storeApp")
.controller("storeCtrl", function($rootScope, $http, storeFactory, _products) {
var products;
storeFactory.getProducts().then(function(_products) {
products = _products.data;
$rootScope.products = products;
});
You can use console.log("something here" + _products.data); to see in your browser console

Router resolve will not inject into controller

I have tried everything to get ui-router's resolve to pass it's value to the given controller–AppCtrl. I am using dependency injection with $inject, and that seems to cause the issues. What am I missing?
Routing
$stateProvider.state('app.index', {
url: '/me',
templateUrl: '/includes/app/me.jade',
controller: 'AppCtrl',
controllerAs: 'vm',
resolve: {
auser: ['User', function(User) {
return User.getUser().then(function(user) {
return user;
});
}],
}
});
Controller
appControllers.controller('AppCtrl', AppCtrl);
AppCtrl.$inject = ['$scope', '$rootScope'];
function AppCtrl($scope, $rootScope, auser) {
var vm = this;
console.log(auser); // undefined
...
}
Edit
Here's a plunk http://plnkr.co/edit/PoCiEnh64hR4XM24aH33?p=preview
When you use route resolve argument as dependency injection in the controller bound to the route, you cannot use that controller with ng-controller directive because the service provider with the name aname does not exist. It is a dynamic dependency that is injected by the router when it instantiates the controller to be bound in its respective partial view.
Also remember to return $timeout in your example, because it returns a promise otherwise your argument will get resolved with no value, same is the case if you are using $http or another service that returns a promise.
i.e
resolve: {
auser: ['$timeout', function($timeout) {
return $timeout(function() {
return {name:'me'}
}, 1000);
}],
In the controller inject the resolve dependency.
appControllers.controller('AppCtrl', AppCtrl);
AppCtrl.$inject = ['$scope', '$rootScope','auser']; //Inject auser here
function AppCtrl($scope, $rootScope, auser) {
var vm = this;
vm.user = auser;
}
in the view instead of ng-controller, use ui-view directive:
<div ui-view></div>
Demo
Here is how I work with resolve. It should receive promise. So I create service accordingly.
app.factory('User', function($http){
var user = {};
return {
resolve: function() {
return $http.get('api/user/1').success(function(data){
user = data;
});
},
get: function() {
return user;
}
}
});
This is main idea. You can also do something like this with $q
app.factory('User', function($q, $http){
var user = {};
var defer = $q.defer();
$http.get('api/user/1').success(function(data){
user = data;
defer.resolve();
}).error(function(){
defer.reject();
});
return {
resolve: function() {
return defer.promise;
},
get: function() {
return user;
}
}
});
These are almost identical in action. The difference is that in first case, service will start fetching date when you call resolve() method of service and in second example it will start fetch when factory object is created.
Now in your state.
$stateProvider.state('app.index', {
url: '/me',
templateUrl: '/includes/app/me.jade',
controller: function ($scope, $rootScope, User) {
$scope.user = User.get();
console.log($scope.user);
},
controllerAs: 'vm',
resolve: {
auser: function(User) {
return User.resolve()
}
}
});

How to use an angular factory correctly?

I've been doing quite a lot of reading about angular dependency injection and factories vs services etc like in this post here - angular.service vs angular.factory
I'm struggling putting it into practise and wonder if you can give me suggestions on how you would do it.
My current code looks like this
var app = angular.module("martysCoolApp", ['firebase', 'ngRoute'])
function mainController($scope, $firebase) {
var db = new Firebase("https://**.firebaseio.com/");
$scope.messages = $firebase(db);
$scope.addItem = function(error) {
if (error.keyCode != 13) return;
$scope.messages.$add({ name: $scope.name, price: $scope.price });
$scope.name = "";
$scope.price = "";
};
}
I decided I wanted to use angular routes and split this basic function up into two different controllers that I would use for my test app. the MainController would just display everything in the firebase db and the AdminController would be able to add messages to it
var app = angular.module("martysCoolApp", ['firebase', 'ngRoute'])
.factory('fireBaseConnectionService', $firebase)
//code in here to connect to firebase and add messages
.controller('MainController', function(fireBaseConnectionService, $scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
//code here to retrieve everything from firebase db
})
.controller('AdminController', function(fireBaseConnectionService, $scope, $routeParams) {
$scope.name = "AdminController";
$scope.params = $routeParams;
//code here to add a row to the db
})
.config(function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
redirectTo: '/menu'
})
.when('/menu', {
path: '/menu',
templateUrl: 'partials/menu.html',
controller: 'MainController'
})
.when('/admin', {
templateUrl: 'partials/admin.html',
controller: 'AdminController'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(false);
});
My problem is I don't want to have to connect to the firebase db in each controller. I would like to have a factory that handles this for me and has maybe functions within that that I can call from my controllers to view everything in db and to add something to the db
factory()
As we’ve seen, the factory() method is a quick way to create and configure a service.
The factory() function takes two arguments:
• name (string)
This argument takes the name of the service we want to register.
• getFn (function)
This function runs when Angular creates the service.
angular.module('myApp')
.factory('myService', function() {
return {
'username': 'auser'
}
});
The getFn will be invoked once for the duration of the app lifecycle, as the service is a singleton
object. As with other Angular services, when we define our service, getFn can take an array or a
function that will take other injectable objects.
The getFn function can return anything from a primitive value to a function to an object (similar to
the value() function).
angular.module('myApp')
.factory('githubService', [
'$http', function($http) {
return {
getUserEvents: function(username) {
// ...
}
}
}]);
service()
If we want to register an instance of a service using a constructor function, we can use service(),
which enables us to register a constructor function for our service object.
The service() method takes two arguments:
• name (string)
This argument takes the name of the service instance we want to register.
• constructor (function)
Here is the constructor function that we’ll call to instantiate the instance.
The service() function will instantiate the instance using the new keyword when creating the
instance.
var Person = function($http) {
this.getName = function() {
return $http({
method: 'GET',
url: '/api/user'
});
};
};
angular.service('personService', Person);
provider
These factories are all created through the $provide service, which is responsible for instantiating
these providers at run time.
angular.module('myApp')
.factory('myService', function() {
return {
'username': 'auser'
}
})
// This is equivalent to the
// above use of factory
.provider('myService', {
$get: function() {
return {
'username': 'auser'
}
}
});
Why would we ever need to use the .provider() method when we can just use the .factory()
method?
The answer lies in whether we need the ability to externally configure a service returned by the
.provider() method using the Angular .config() function. Unlike the other methods of service
creation, we can inject a special attribute into the config() method.
from ng-book
All you have to do is just move the firebase connection into the service, and inject that service wherever you want . The connection line will execute the first time your app runs, given that you front load the service when your app runs, as you seem to be doing now:
.factory('fireBaseConnectionService', function($firebase){
var db = $firebase(new Firebase("https://**.firebaseio.com/"));//creating
//the firebase connection this line executes only once when the service is loaded
return{
getMessage:function(){
return db.whatever;
}
}
})
If you load the service script dynamically, on route where you need it, it will only connect to the database when it reaches that route. The code above will create one connection to the database, as the connection line is executed only once.
Just for anyone interested with the help of the answers above and this link - Firebase _ AngularJS this is what I ended up doing
var app = angular.module("martysCoolApp", ['firebase', 'ngRoute'])
.factory('fireBaseConnectionService', ["$firebase", function($firebase) {
var db = new Firebase("https://***.firebaseio.com/");
return {
getMessages: function() {
return $firebase(db);
},
addMessage: function(message) {
var messages = $firebase(db);
messages.$add(message);
}
}
}])
.controller('MainController', ["fireBaseConnectionService", "$scope", function (fireBaseConnectionService, $scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
$scope.messages = fireBaseConnectionService.getMessages();
}])
.controller('AdminController', ["fireBaseConnectionService", "$scope", function(fireBaseConnectionService, $scope, $routeParams) {
$scope.name = "AdminController";
$scope.params = $routeParams;
$scope.addItem = function(error) {
if (error.keyCode != 13) return;
fireBaseConnectionService.addMessage({ name: $scope.name, price: $scope.price });
$scope.name = "";
$scope.price = "";
}
}])
.config(function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
redirectTo: '/menu'
})
.when('/menu', {
path: '/menu',
templateUrl: 'partials/menu.html',
controller: 'MainController'
})
.when('/admin', {
templateUrl: 'partials/admin.html',
controller: 'AdminController'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(false);
});

Angular JS Method GET inside RUN after CONFIG

I need to do a request inside the RUN method to retrieve de user data from an api.
The first page (home), depends on the user data.
This is the sequence of dispatchs in my console:
CONFIG
RUN
INIT GET USER DATA
SIDEBAR
HOME
SUCCESS GET USER DATA
My problem is, i need to wait user data before call sidebar and home (controller and view) and i don't know how can i do this.
UPDATE
I have this until now:
MY CONFIG:
extranet.config(['$httpProvider', '$routeProvider', function ($httpProvider, $routeProvider) {
// My ROUTE CONFIG
console.log('CONFIG');
}]);
My RUN:
extranet.run(function($rootScope, $location, $http, Cookie, Auth, Session) {
console.log('RUN');
var token = Cookie.get('token');
// The login is done
var success = function (data) {
Session.create(data);
console.log('USER DATA SUCCESS');
};
var error = function () {
$location.path('/login');
};
// GET USER DATA
Auth.isAuthenticated().success(success).error(error);
});
MY CONTROLLER MAIN:
extranet.controller('MainCtrl', function ($scope, $location) {
console.log('MAIN CONTROLLER');
});
By using resolver
extranet.config(['$httpProvider', '$routeProvider', function ($httpProvider, $routeProvider) {
// My ROUTE CONFIG
$routeProvider.when('/', {
templateUrl: "/app/templates/sidebar.html",
controller: "siderbarController",
title: "EventList",
resolve: {
events: function ($q, Cookie,Session) {
var deffered = $q.defer();
Cookie.get('token').$promise
.then(function (events) {
Session.create(data);
console.log('USER DATA SUCCESS');
deffered.resolve(events);
}, function (status) {
deffered.reject(status);
});
return deffered.promise;
}
}
}]);
I hope you get some idea.
If you are using AngularJS methods for server requests you will get a promise. A promise gets resolved as soon as the response is recieved. All defined callbacks "wait" until the resolve.
Naive solution
So, you will use $http or even $resource if you have a REST-like backend:
var promise = $http.get(userDataUrl, params)
$rootScope.userDataPromise = promise;
After that you can use that promise whereever you need the data:
$rootScope.userDataPromise.then(myCallback)
Better solution
Using $rootScope for that purpose is not an elegant solution though. You should encapsulate the Userdata stuff in a service and inject it whereever you need it.
app.factory('UserData', ['$http',
function($http) {
var fetch = function() {
return $http.get(userDataUrl, params)
};
return {
fetch: fetch
};
}
]);
Now you can use that service in other modules:
app.controller('MainCtrl', ['$scope', 'UserService',
function ($scope, UserService) {
var update = function(response) {
$scope.userData = response.userData;
}
var promise = UserService.fetch();
promise.then(update)
}
);

AngularJS $http.delete and $window.location.reload()

I have an interesting issue with the $http.delete() and $window.location.reload() functions. Basically I am calling a delete method that in turn calls the $http.delete() call which - using a REST API interface - removes data from a database (mongoDB). For reasons unknown this is what's happening:
delete is successful in the database
this is verified as the data is no longer in the database
also monitored using Chrome DevTools it shows status: 200
$window.location.reload() gets called and nothing happens
Chrome DevTools shows a GET call to the root of the domain but the status is 'pending'
The page does not time out, it basically keeps on loading and loading and loading. Once I hit refresh / CTRL-F5 all goes back to normal and I can see that my item has been deleted.
Some excerpts from my code:
app.js
angular.module('contacts', ['ngRoute', 'contacts.factory', 'contacts.filters', 'ui.bootstrap']).
config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
templateUrl: '/p/list',
controller: ListCtrl,
}).
otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]);
controllers.js
function ListCtrl($scope, $modal, contactFactory) {
//code removed
$scope.delete = function(c) {
var id = c._id;
var modalInstance = $modal.open({
templateUrl: 'deleteContactModal',
controller: deleteContactModalCtrl,
resolve: {
contact: function() {
return contactFactory.getContact(id);
}
}
});
}
}
var deleteContactModalCtrl = function($scope, $route, $modalInstance, $window, contact, contactFactory) {
$scope.name = contact.data.contact.name;
$scope.deleteContact = function() {
contactFactory.deleteContact(contact.data.contact._id).success(function() {
//have also tried: $window.location.reload(true);
//as well as window.location.href('/') - didn't work either
$modalInstance.close($window.location.reload());
});
};
}
factory.js
angular.module("contacts.factory", []).
factory('contactFactory', function($http){
return {
//code removed
deleteContact: function(id) {
return $http.delete('/api/contact/' + id);
}
}
});
backend - app.js
//usual express setup
app.delete('/api/contact/:id', api.delete); //delete contact
backend - api.js
//code removed
exports.delete = function (req, res) {
var id = req.params.id;
if (id) {
ContactModel.findById(id, function (err, contact) {
contact.remove(function (err) {
if (!err) {
res.json(true);
} else {
res.json(false)
console.log(err);
}
});
});
}
};
At the moment I'm not even sure if this issue is related to the frontend or to the backend. As mentioned before - the backend portion is working fine - the data is deleted from the DB.
Okay the solution seems to be the following:
$scope.deleteContact = function() {
contactFactory.deleteContact(contact.data.contact._id).success(function() {
$modalInstance.close();
contactFactory.getContacts().success(function(contacts) {
return $scope.contacts = contacts;
});
$window.location.reload();
});
};
I need to get the getContacts() method from my factory again during the delete method.

Categories