I have two mongoose schemas running in on my server end. I would like to add two $http.get request in my app.js and eventually display two tables from my collection in MongoDB on a webpage. Only one get function is called without errors.
server.js
//Data Schema
var tempSchema = new mongoose.Schema({
topic: String,
message: Number,
when: Date
}, {collection: "temperature"});
var humiditySchema = new mongoose.Schema({
topic: String,
message: Number,
when: Date
}, {collection: "humidity"});
var temperature =mongoose.model('temperature', tempSchema);
var humidity =mongoose.model('humidity', humiditySchema);
app.js
app.controller("FormController", function ($http, $scope){
$http.get("/api/temperature")
.then(function (response) {
$scope.temperatures = response.data;
});
})
app.controller("FormController", function ($http, $scope){
$http.get("/api/humidity")
.then(function (response) {
$scope.humiditys = response.data;
});
})
Also thinking of how I can display both collections on the webpage. Using ng-repeat. Unfortunately I cannot paste my HTML code here.
I would appreciate any help I can get. Thanks
Another way you could handle the $http requests is by creating an Angular Factory.
angular.module('myApp.services',[])
add.factory('ApiService', function($http) {
return {
getHumidity: function() {
return $http.get("/api/humidity");
},
getTemperature: function() {
return $http.get("/api/temperature");
}
}
})
Then inside your controller, you should do the following (Note that you must inject the factory as a dependency for the controller)
angular.module('myApp.controllers',[])
.controller("FormController", function (ApiService, $scope){
function getHumidity() {
var promise = ApiService.getHumidity();
promise.then(
function(response) {
$scope.humiditys = response.data;
},
function(errorPayload) {
console.log(errorPayload);
});
};
function getTemperature() {
var promise = ApiService.getTemperature();
promise.then(
function(response) {
$scope.temperatures = response.data;
},
function(errorPayload) {
console.log(errorPayload);
});
};
getHumidity();
getTemperature();
})
then where you define your angular App (app.js in most of the cases):
angular.module('myApp', ['myApp.controllers','myApp.services'])
.run(...)
.config(...)
...
Related
I'm developing an e-commerce web app using AngularJS (v1.6.7) and Parse Server (v2.3.3).
I created Category and Product class in Parse Server. I'm trying to fetch in a certain amount of products per category.
For example, in homepage, 20 products will be retrieved per category. The amount of products changes in other pages.
I want to do it using a factory that fetches given amount of products in any category (amount and category of products will be passed to the function as parameters). So I'll be able to reuse it inside other controllers.
ProductsFactory factory:
sebetimapp.factory('ProductsFactory', ['$q', function($q){
Parse.initialize('MY_APP_ID', 'JS_KEY');
Parse.serverURL = 'https://parseapi.back4app.com/';
let fac = {};
fac.getProducts = function(cat, lmt) {
let Category = Parse.Object.extend('Category'),
qr = new Parse.Query(Category);
qr.get(cat, {
success: function (res) {
let product_dfd = $q.defer(),
Product = Parse.Object.extend('Product'),
query = new Parse.Query(Product);
query.include('category');
query.equalTo('category', res);
if (lmt) {
query.limit(lmt);
}
query.find({
success: function(results) {
product_dfd.resolve(results);
},
error: function(err) {
product_dfd.reject(results);
}
});
return product_dfd.promise;
},
error: function(object, error) {
//
}
});
};
return fac;
}]);
productsCtrl controller:
sebetimapp.controller('productsCtrl', ['$scope', '$log', '$location', '$q', 'ProductsFactory', function($scope, $log, $location, $q, ProductsFactory) {
let params = $location.search(); // To grab category ID from URL.
ProductsFactory.getProducts(params.cat, 20).then(function(response) {
$log.log('Successfully retrieved products.');
}, function(error) {
$log.log('Unable to get products.');
});
}]);
When I execute it, an error occurs:
TypeError: Cannot read property 'then' of undefined
But if I don't use this factory and define getProducts() function inside my controller, it works fine.
Why is this happening? I'm new to AngularJS. Any help would be appreciated.
The .then() method is only available on Promises. Your function appears to be not returning anything (and hence, .then() is unavailable).
This might help:
sebetimapp.factory('ProductsFactory', ['$q', function($q) {
Parse.initialize('MY_APP_ID', 'JS_KEY');
Parse.serverURL = 'https://parseapi.back4app.com/';
var fac = {};
fac.getProducts = function(cat, lmt) {
var Category = Parse.Object.extend('Category'),
qr = new Parse.Query(Category);
return qr.get(cat)
.then(function(res) {
var Product = Parse.Object.extend('Product'),
query = new Parse.Query(Product);
query.include('category');
query.equalTo('category', res);
if (lmt) {
query.limit(lmt);
}
return query.find();
});
};
return fac;
}]);
Most methods in the Parse JS API return promises. You can use those directly (and not use the success and error callbacks). It's been ages since I worked on Parse (I thought it was no longer available) so you may have to figure out the details yourself.. Handy Link: http://docs.parseplatform.org/js/guide/#promises
TLDR; Your factory function needs to return a promise but is returning nothing and hence .then() is unavilable
EDIT: Here is another way to the same thing with minimal changes to you original code (this is not the best way to do this, however)
sebetimapp.factory('ProductsFactory', ['$q', function($q) {
Parse.initialize('MY_APP_ID', 'JS_KEY');
Parse.serverURL = 'https://parseapi.back4app.com/';
var fac = {};
fac.getProducts = function(cat, lmt) {
var Category = Parse.Object.extend('Category'),
qr = new Parse.Query(Category),
// Move the deffered object out of the inner function
product_dfd = $q.defer();
qr.get(cat, {
success: function(res) {
var Product = Parse.Object.extend('Product'),
query = new Parse.Query(Product);
query.include('category');
query.equalTo('category', res);
if (lmt) {
query.limit(lmt);
}
query.find({
success: function(results) {
product_dfd.resolve(results);
},
error: function(err) {
product_dfd.reject(results);
}
});
},
error: function(object, error) {}
});
// Return the deferred object
return product_dfd.promise;
};
return fac;
}]);
I've written a backend service which is used by a Angular.JS frontend using a factory, like so:
angular.module('app.social', ['ngResource'])
.factory('Social', function($http) {
return {
me: function() {
return $http.get('http://localhost:3000/me');
},
likeVideo: function(link) {
return $http.post('http://localhost:3000/like/video', { link : link });
},
post: function(link) {
return $http.post('http://localhost:3000/post', { link : link });
},
postVideo: function(link) {
return $http.post('http://localhost:3000/post/video', { link : link });
},
friends: function() {
return $http.get('http://localhost:3000/friends');
},
taggableFriends: function() {
return $http.get('http://localhost:3000/friends/taggable');
},
videos: function() {
return $http.get('http://localhost:3000/videos');
}
};
});
The Social.me endpoint receives profile information from the REST backend. This function is used in various Angular controllers, however (profile page, item detail page, header account button etc.). This means that for every view, profile information is requested from http://localhost:3000/me. Is this good practice, or is it a better idea to cache the information within the factory?
EDIT: Updated code (based on answer from #Rebornix):
angular.module('app.social', ['ngResource'])
.service('SocialService', function() {
var serviceData = {
me: null
};
return serviceData;
})
.factory('Social', function($http, SocialService) {
return {
me: function() {
if (SocialService.me === null) {
return $http.get('http://localhost:3000/me').then(function(response) {
SocialService.me = response.data;
return SocialService.me;
});
} else {
return SocialService.me;
}
}
}
};
});
In the controller, I use:
angular.module('app.profile', [])
.controller('ProfileCtrl', ['$window', '$scope', 'Social', function($window, $scope, Social) {
$scope.me = Social.me();
}])
And the view:
<div ng-controller="ProfileCtrl">
<h1 class="profile-name">{{ me.name }}</h1>
</div>
But the view is not updated as the Facebook.me value get initialized on the first request. I guess I have to manually trigger $scope.$apply() somehow?
You can create a service as storage across controllers like
angular.module('app.social', ['ngResource'])
.service("SocialService", function() {
var info = {
me: null,
friends: []
};
return info;
})
.factory('Social', function($http, SocialService) {
return {
me: function() {
$http.get('http://localhost:3000/me').then(function(response){
SocialService.me = response.data;
});
},
Then in all your controllers, reference infoService instead of calling API again. What you need to is fetching latest data and refresh infoService, all controllers scope will be notified with this change.
In your controller
angular.module('app.profile', [])
.controller('ProfileCtrl', ['$window', '$scope', 'SocialService', 'Social', function($window, $scope, SocialService, Social) {
$scope.SocialService = SocialService;
// Kick off social factory to update user info, you can move it into
// any other functions like `ng-click`.
Social.me();
}])
Then in your view
{{SocialService.me}}
(function (app) {
'use strict';
app.factory('myService', MyService);
MyService.$inject = ['$q', 'serviceResource'];
function MyService($q, serviceResource) {
var jobs = [];
var service = {
getJobs: getJobs
};
return service;
//////////////////////////////////////
function getJobs(refresh) {
if (refresh) {
return serviceResource.autosysJobs().$promise.then(function (data) {
jobs = data;
return jobs;
}, function (err) {
throw err;
});
}
else {
var deferrer = $q.defer();
deferrer.resolve(jobs);
return deferrer.promise;
}
}
}
}(angular.module('app')));
you can pass a bool argument to tell weather to get local copy or fresh copy
It all depends upon the frequency of data change in back end data change and degree of tolerance of data inconsistency in your application. if the source data is changing too frequently and you can't afford inconsistent data then you have no choice other than to get fresh copy every time, but if that's not the case then you can cash data locally
I'm using Angular wp-api module and each time my $resource request responds I can see the ResponseHeaders in Chrome with X_Total_Pages and other header information. But I cannot add them to the scope.
Here is my controller...
.controller('newslettersController', ['$scope','$stateParams','$sce','WPFactory', function ($scope,$stateParams,$sce,WPFactory) {
$scope.newsletters = WPFactory.query({
param1: 'posts',
page: $scope.pageNum,
'filter[cat]': 8,
'filter[posts_per_page]' : 10,
'filter[orderby]': 'ID'
}, function(data, reponseHeaders) {
$scope.header = reponseHeaders('X_Total_Pages');
});
});
}]);
And my factory...
.factory("WPFactory", function($resource) {
var dataResponse = $resource('http://www.example.com/wp-json/:param1/:param2/:param3/:param4/:param6/:param7', {}, {
get: {
method: 'GET'
}
});
return dataResponse;
})
is this jeffsebrings angular module? If it is I think you need to inject your service with wpAPIResource:
.factory("WPFactory", function($resource, wpAPIResource)
and use it to query the json rest api (wp-api).
Also, not sure if your controller is passing the query object quite right:
I would change up your factory something like this:
.factory("WPFactory", function(wpAPIResource) {
var posts_query = function(args) {
return wpAPIResource.query(args);
};
return posts_query;
})
I am looking to have parameters in the route, by using a colon before the variable name
// dynamic pages for each ITEM, once selected
// from $routeParams.itemID in ItemCtrl
.when('/:itemID', {
templateUrl: 'views/item.html',
controller: 'ItemController'
})
When a div-box is clicked, Angular should route to the specific item
<div class="itemBox" ng-click="getItem(item._id)">
Right now, the call to the node/express API seems to be working
[16:36:18.108] GET http://localhost:8080/api/items/534240001d3066cc11000002 [HTTP/1.1 304 Not Modified 4ms]
But this error logs in the console:
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:691:11)
...
at Promise.<anonymous> (/Users/Username/Downloads/project/v19/app/routes.js:41:8)
...
Line 41 (for 41:8?) in routes.js is res.json(item);
// load the item model
var Item = require('./models/item');
// get One item
app.get('/api/items/:item_id', function(req, res) {
// use mongoose to get the one item from the database
Item.findById({
_id : req.params.item_id
},
function(err, item) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err)
res.json(item); // return the item in JSON format
});
});
Though it seems like the issue might be in the Controller because all of the other API calls work.. And so I tried passing $routeParams all over the place!
angular.module('ItemCtrl', [])
// inject the Item service.factory into our controller
.controller('ItemController', function($scope, $routeParams, $http, Items, isEmptyObjectFilter) {
// get an Item after clicking it
$scope.getItem = function(id, $routeParams) {
Items.getOne(id, $routeParams)
// if successful getByID, call our function to get the Item data
.success(function(data, $routeParams) {
// assign our Item
$scope.item = data;
// for use with a parameter in appRoutes.js using itemID as the variable
$scope.itemID = $routeParams.itemID;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
});
Or maybe it's the service? Does this need to pass $routeParams as function(id, $routeParams)
angular.module('ItemService', [])
// super simple service
// each function returns a promise object
.factory('Items', function($http) {
return {
get : function() {
return $http.get('/api/items');
},
getOne : function(id) {
return $http.get('/api/items/' + id);
},
create : function(itemData) {
return $http.post('/api/items', itemData);
},
delete : function(id) {
return $http.delete('/api/items/' + id);
}
}
});
Would really appreciate some assistance debugging this.. Thanks
It looks like you are getting the data correctly. The problem is that you want the route to change after successfully getting the API call?
$routeParams won't change the route for you. That just gets the data. Use $location to change the route.
.controller('ItemController', function($scope, $routeParams, $location, $http, Items, isEmptyObjectFilter) {
$scope.getItem = function(id) {
Items.getOne(id)
.success(function(data) {
$scope.item = data;
$scope.itemID = $routeParams.itemID;
// redirect
$location.path('/' + $routeParams.itemID);
});
});
});
Since all of your data seems to be ready to go, you just need Angular to redirect to the route. $location should be the way to go.
That message is because you are getting an error and executing the res.send() method, and after that you have res.json(), express is trying to respond twice.
Try changing:
if (err)
res.send(err)
To:
if (err) {
res.json({ error: err });
} else {
var object = item.toObject();
res.json(object);
}
Angular resource example:
angular.module('ItemService')
.factory('Items', ['$resource', function($resource) {
return $resource('/api/items/:itemID', {
itemID: '#_id'
}, {
update: {
method: 'PUT'
}
});
}]);
Now you can do this in your controller:
// Find
Items.get({
itemID: $routeParams.itemID
}, function(item) {
$scope.item = item;
});
// Update
$scope.item.name = 'New name';
$scope.item.$update();
// Remove
$scope.item.$remove();
I'am not pro in Angular and am still lerning. Hope I get some help here.
I want to build an App with different views. I need to detect the browser and also fetch some data from a server. For this I created a service, where I do this work.
My desire is to use the data of the service all views. How is proper way to store and cache the data so that I can use it in all my Views/Controllers?
Here is what I got so far.
My Service:
.factory('DataService', function($http, $q, $timeout) {
var data = { };
return {
notes: function() {
// This exposed private data
return data;
},
addItem: function(itemname, itemvalue) {
// This is a public function that modifies private data
data[itemname] = itemvalue;
}
getPlatform: function() {
var getPlatformData = function() {
var deferred = $q.defer();
BrowserDetect.init();
deferred.resolve(BrowserDetect.OS);
return deferred.promise;
};
return {
getPlatformData: getPlatformData
};
},
getServerData: function() {
//if(!data.getServerData){
var getData = function() {
var deferred = $q.defer();
$http({
url: 'js/fakeGet.json',
method: 'get',
dataType: 'json',
}).success(function(data) {
data.scanResponse = data;
deferred.resolve(data);
})
return deferred.promise;
};
return {
getData: getData
};
//}
// return data.scanResponse;
}
};
});
My controller:
DataService.getPlatform().getPlatformData().then(function(platform) {
console.log('Another browserDetect request');
$scope.platform = platform;
DataService.addItem("platform", $scope.userPlatform);
});
First of all, as nordyke mentioned in his answer, you'd better split the service to smaller ones.
Second, you're asking for how to caching the data, and since you're using promise, $q.when() is what you need. I will take the getPlatform as an example to get you started:
.factory('DataService', function($http, $q, $timeout) {
var os; // this variable is used to store the result
return {
getPlatform: function() {
var getPlatformData = function() {
if (!os) { // no previous data available, look into other service to fetch the data
var deferred = $q.defer();
BrowserDetect.init();
os = BrowserDetect.OS; // store data
deferred.resolve(os);
return deferred.promise;
}
return $q.when(os); // there is previous data, return it as promise
};
return {
getPlatformData: getPlatformData
};
}
};
});
In this way, OS information is cached, and
DataService.getPlatform().getPlatformData().then(function(platform) {
...
});
will only fetch the platform information once during the life-time of the DataService. You can apply the same idea to getServerData as well to cache the data from the server.
Caching your data in a service singleton is a good approach, and I like your straightforward implementation of it. My only recommendation would be to split up your 3 concerns into separate services.
Browser Detection
Server Requests (which will be split up even more once you have more requests.)
Data Caching