Using asynchronous data from one factory in another factory - javascript

I'm trying to use geolocation data from one factory in angular in another factory that queries a weather API for data. I cannot figure out how to share the lat/lng variables between the two factories, I know you have use $scope but I cannot get the angular-promise to work correctly. Currently there are static lat/lng variables. The locate function in the controller doesn't even print to console, I think there's something wrong with my promise function.
Here are the factories:
'use strict';
app.config(['$resourceProvider', function ($resourceProvider) {
$resourceProvider.defaults.stripTrailingSlashes = false;
}]);
app.factory("geolocationService", ['$q', '$window', '$rootScope', function ($q, $window, $rootScope) {
return {
currentLocation: function() {var deferred = $q.defer();
if (!$window.navigator) {
$rootScope.$apply(function() {
deferred.reject(new Error("Geolocation is not supported"));
});
} else {
$window.navigator.geolocation.getCurrentPosition(function (position) {
$rootScope.$apply(function() {
deferred.resolve(position);
var geoJ = $scope.data;
//console.log(position);
});
}, function (error) {
$rootScope.$apply(function() {
deferred.reject(error);
});
});
}
return deferred.promise;
}
}
}]);
app.factory('weatherFactory', ['$http','geolocationService', function ($http, $scope, geolocationService) {
//var currentLocation = geolocationService.currentLocation();
var apiKey = 'd079ba76e47f06f2ea3483892f1b1d40';
var lat = '40',
lon = '-79';
return {
currentForecast: function(callback){
var url = ['https://api.forecast.io/forecast/', apiKey, '/', lat, ',', lon, '?callback=JSON_CALLBACK'].join('');
$http.jsonp(url)
.success(function (data){
callback(null, data);
//console.log("weatherFactory API Call: ");
//console.log(data);
})
.error(function (error) {
callback(error);
});
}
};
}]);
And here is the controller
app.controller('weatherCtrl', function ($scope, $window, weatherFactory, geolocationService) {
//console.log(geolocationService.currentLocation());
//var location = geolocationService.currentLocation();
//console.log("location object: ");
//console.log(location);
var locate = function(){
geolocationService.currentLocation().then(function(location){
$scope.location = location;
console.log($scope.location);
});
};
var pollForecast = function pollForecast() {
var commutes = calculateNextCommutes();
weatherFactory.currentForecast(function (err, data) {
if (err) {
$scope.forecastError = err;
} else {
$scope.forecast = data;
$scope.nextCommute = findCommuteWeather(commutes.nextCommute, $scope.forecast.hourly.data);
$scope.nextNextCommute = findCommuteWeather(commutes.nextNextCommute, $scope.forecast.hourly.data);
}
});
};
$scope.init = function () {
pollForecast();
setInterval(function () {
console.log('polling weather every hour')
pollForecast();
}, 1000 * 60 * 60); //poll every hour
}
});
I'm very new to Angular and would appreciate any help from the community, I'd like to be more active on here! Thanks in advance.
Best Regards,
-MC

First of all, DONT USE $SCOPE IN FACTORY, $scope is only available on controllers.
The solution for you problem is very simple. Have weatherFactory expose the lat/long by returning them:
return {
lat: lat,
lon: lon,
currentForecast: function(callback){
var url = ['https://api.forecast.io/forecast/', apiKey, '/', lat, ',', lon, '?callback=JSON_CALLBACK'].join('');
$http.jsonp(url)
.success(function (data){
callback(null, data);
//console.log("weatherFactory API Call: ");
//console.log(data);
})
.error(function (error) {
callback(error);
});
}
};
And then, inject weatherFactory into geolocationService and you'll be able to access lat/lon:
app.factory("geolocationService", ['$q', '$window', '$rootScope', 'weatherFactory', function ($q, $window, $rootScope , weatherFactory) {
return {
currentLocation: function() {var deferred = $q.defer();
var lat = weatherFactory.lat;
var lon = weatherFactory.lon;
if (!$window.navigator) {
$rootScope.$apply(function() {
deferred.reject(new Error("Geolocation is not supported"));
});
} else {
$window.navigator.geolocation.getCurrentPosition(function (position) {
$rootScope.$apply(function() {
deferred.resolve(position);
var geoJ = $scope.data;
//console.log(position);
});
}, function (error) {
$rootScope.$apply(function() {
deferred.reject(error);
});
});
}
return deferred.promise;
}
}
}]);

How about this:
app.factory("geolocationService", ['$q', '$window', '$rootScope', function ($q, $window, $rootScope) {
return {
currentLocation: function() {
var deferred = $q.defer();
if (!$window.navigator) {
$rootScope.$apply(function() {
deferred.reject(new Error("Geolocation is not supported"));
});
} else {
$window.navigator.geolocation.getCurrentPosition(function (position) {
$rootScope.$apply(function() {
deferred.resolve(position);
});
}, function (error) {
$rootScope.$apply(function() {
deferred.reject(error);
});
});
}
return deferred.promise;
}
}
}]);
app.service('weatherService', ['$http','geolocationService', function ($http, $scope, geolocationService) {
var apiKey = '...';
return function(callback){
//Note - a better, more angularish way to do this is to return the promise
//itself so you'll have more flexability in the controllers.
//You also don't need callback param because angular's $http.jsonp handles
//that for you
geolocationService.currentLocation().then(function(location){
var url = ['https://api.forecast.io/forecast/', apiKey, '/', location.lat, ',', location.lon, '?callback=JSON_CALLBACK'].join('');
return $http.jsonp(url)
.then(function(data){ callback(null,data); })
catch(callback);
}
};
}]);

Related

Update function AngularJs is not working [duplicate]

I have a function which updates the object, the problem is when I go back from the update form field to the detailed view, it initializes the old object instead of the updated object.
I want to populate the cars list in the CarService instead of the app.js
This is my carService:
window.app.service('CarService', ['HTTPService', '$q',
'$http', function (HTTPService, $q, $http) {
'use strict';
this.cars = [];
this.get = function () {
var deferred = $q.defer();
HTTPService.get('/car').then(function resolve(response) {
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
};
this.add = function (formCar) {
var deferred = $q.defer();
console.log("CarService response 1 : ");
$http.post('/#/car', formCar).then(function resolve(response){
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
this.showDetails = function (carId){
var deferred = $q.defer();
$http.get('/car/view/{{carId}}').then(function resolve(response){
HTTPService.get('/car/view/' + carId).then(function
resolve(response) {
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
this.put = function (carformUpdate, opleidingsprofielId) {
var deferred = $q.defer();
$http.put('/#/car/:carId/update', carformUpdate).then(function resolve(response){
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
}]);
This is my updateCar controller:
window.app.controller('updateCarCtrl', ['$scope', '$routeParams',
'CarService', '$location', function ($scope, $routeParams, CarService,
$location) {
'use strict';
$scope.carId = $routeParams.carId;
initCar($scope.carId);
function initCar(carId) {
CarService.showDetails(carId).then(function success(car) {
$scope.car = car;
}, function error(response) {
});
}
$scope.updateCar = function (carId) {
carId = $scope.carId;
if($scope.car !== null){
CarService.put($scope.car, carId).then(function
success(response) {
$scope.car = response;
$location.path('/car/view/' + carId);
alert("Car updated");
}, function error(response) {
$scope.error = response.statusText;
$scope.myform = {};
});
}
};
}]);
This is my carView controller:
window.app.controller('carViewCtrl', ['$scope', '$routeParams', '$location',
'CarService', function ($scope, $routeParams, $location, CarService) {
'use strict';
$scope.carId = $routeParams.carId;
initCar($scope.carId);
function initCar(carId) {
CarService.showDetails(carId).then(function success(car) {
$scope.car = car;
}, function error(response) {
});
}
}]);
My carView initializes the object again when it gets redirected with $location.path('/car/view/' + carId); but as the original object and not the updated object.
I'm trying to do this on an ngMock backend.
My app.js looks like this:
App.js
routing:
.when('/car', {
templateUrl: 'pages/car/car.html'
})
.when('/car/view/:carId', {
templateUrl: 'pages/car/carView.html',
controller: 'carViewCtrl',
controllerAs: 'ctrl'
})
.when('/car/addCar', {
templateUrl: 'pages/car/carAdd.html'
})
.when('/car/:carId/update', {
templateUrl: 'pages/car/carUpdate.html',
controller: 'updateCarCtrl',
conrtollerAs: 'ctrl'
})
app.run: this is where my mock backend is defined
window.app.run(function($httpBackend) {
var cars = [
{
id: 0,
name: ‘car0’,
address: 'adress0',
tel: 'tel0',
email: 'email0'},
{
id: 1,
name: ‘car1’,
address: 'adress1',
tel: 'tel1',
email: 'email1'
}];
var carUrl = “/#/car”;
$httpBackend.whenGET(carUrl).respond(function(method,url,data) {
return [200, cars, {}];
});
$httpBackend.whenGET(/\/#\/car\/view\/(\d+)/, undefined,
['carId']).respond(function(method, url, data, headers, params) {
return [200, cars[Number(params.carId)], {
carId : params.carId
}];
});
$httpBackend.whenPUT('/#/car/:carId/update').respond(function(method, url,
data, carId) {
var car = angular.fromJson(data);
return [200, car, {}];
});
Thanks for any help!
It looks like your update function calls the CarService.put, which in turn calls a HTTPService.put. In your mocked backend you have this:
$httpBackend.whenPUT
-> add new car;
So it always adds a new car, and doesn't update one. This means that when you do the get, you probably get the first car back that matches the given id, which isn't the updated one.
In pseudo code:
// carService.cars = [{id:1,name:"name"}]
var myCar = carService.get(1); // returns {id:1,name:"name"}
myCar.name = "otherName";
carService.put(car); // -> cars.push(car); -> cars = [{id:1,name:"name"},{id:1,name:"otherName"}]
goToDetails(1);
var myCar = carService.get(1); // iterate over the cars, and return the one with id = 1,
// which is {id:1,name:"name"}

AngularJS update function is (still)not working

I have a function which updates the object, the problem is when I go back from the update form field to the detailed view, it initializes the old object instead of the updated object.
I want to populate the cars list in the CarService instead of the app.js
This is my carService:
window.app.service('CarService', ['HTTPService', '$q',
'$http', function (HTTPService, $q, $http) {
'use strict';
this.cars = [];
this.get = function () {
var deferred = $q.defer();
HTTPService.get('/car').then(function resolve(response) {
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
};
this.add = function (formCar) {
var deferred = $q.defer();
console.log("CarService response 1 : ");
$http.post('/#/car', formCar).then(function resolve(response){
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
this.showDetails = function (carId){
var deferred = $q.defer();
$http.get('/car/view/{{carId}}').then(function resolve(response){
HTTPService.get('/car/view/' + carId).then(function
resolve(response) {
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
this.put = function (carformUpdate, opleidingsprofielId) {
var deferred = $q.defer();
$http.put('/#/car/:carId/update', carformUpdate).then(function resolve(response){
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
}]);
This is my updateCar controller:
window.app.controller('updateCarCtrl', ['$scope', '$routeParams',
'CarService', '$location', function ($scope, $routeParams, CarService,
$location) {
'use strict';
$scope.carId = $routeParams.carId;
initCar($scope.carId);
function initCar(carId) {
CarService.showDetails(carId).then(function success(car) {
$scope.car = car;
}, function error(response) {
});
}
$scope.updateCar = function (carId) {
carId = $scope.carId;
if($scope.car !== null){
CarService.put($scope.car, carId).then(function
success(response) {
$scope.car = response;
$location.path('/car/view/' + carId);
alert("Car updated");
}, function error(response) {
$scope.error = response.statusText;
$scope.myform = {};
});
}
};
}]);
This is my carView controller:
window.app.controller('carViewCtrl', ['$scope', '$routeParams', '$location',
'CarService', function ($scope, $routeParams, $location, CarService) {
'use strict';
$scope.carId = $routeParams.carId;
initCar($scope.carId);
function initCar(carId) {
CarService.showDetails(carId).then(function success(car) {
$scope.car = car;
}, function error(response) {
});
}
}]);
My carView initializes the object again when it gets redirected with $location.path('/car/view/' + carId); but as the original object and not the updated object.
I'm trying to do this on an ngMock backend.
My app.js looks like this:
App.js
routing:
.when('/car', {
templateUrl: 'pages/car/car.html'
})
.when('/car/view/:carId', {
templateUrl: 'pages/car/carView.html',
controller: 'carViewCtrl',
controllerAs: 'ctrl'
})
.when('/car/addCar', {
templateUrl: 'pages/car/carAdd.html'
})
.when('/car/:carId/update', {
templateUrl: 'pages/car/carUpdate.html',
controller: 'updateCarCtrl',
conrtollerAs: 'ctrl'
})
app.run: this is where my mock backend is defined
window.app.run(function($httpBackend) {
var cars = [
{
id: 0,
name: ‘car0’,
address: 'adress0',
tel: 'tel0',
email: 'email0'},
{
id: 1,
name: ‘car1’,
address: 'adress1',
tel: 'tel1',
email: 'email1'
}];
var carUrl = “/#/car”;
$httpBackend.whenGET(carUrl).respond(function(method,url,data) {
return [200, cars, {}];
});
$httpBackend.whenGET(/\/#\/car\/view\/(\d+)/, undefined,
['carId']).respond(function(method, url, data, headers, params) {
return [200, cars[Number(params.carId)], {
carId : params.carId
}];
});
$httpBackend.whenPUT('/#/car/:carId/update').respond(function(method, url,
data, carId) {
var car = angular.fromJson(data);
return [200, car, {}];
});
Thanks for any help!
It looks like your update function calls the CarService.put, which in turn calls a HTTPService.put. In your mocked backend you have this:
$httpBackend.whenPUT
-> add new car;
So it always adds a new car, and doesn't update one. This means that when you do the get, you probably get the first car back that matches the given id, which isn't the updated one.
In pseudo code:
// carService.cars = [{id:1,name:"name"}]
var myCar = carService.get(1); // returns {id:1,name:"name"}
myCar.name = "otherName";
carService.put(car); // -> cars.push(car); -> cars = [{id:1,name:"name"},{id:1,name:"otherName"}]
goToDetails(1);
var myCar = carService.get(1); // iterate over the cars, and return the one with id = 1,
// which is {id:1,name:"name"}

Send data through a POST request from Angular factory

I have this in the controller
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
$scope.formTodoText = '';
};
});
and this in the factory
angular.module('myApp')
.factory('TaskFactory', function ($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
console.log(1, params);
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log(2);
console.log('data', data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTask: function(taskData) {
console.log('taskData', taskData);
return sendTasks('/task/save', {
taskData : taskData
})
}
}
});
all I need is to know, how to send the data from the controller to the factory in order to do the POST to the specified route ?
You just need to call the function/method inside factory with the required params.
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
TaskFactory.sendTask({data : $scope.formTodoText})
$scope.formTodoText = '';
};
});
You can follow Dan Wahlin blog post.
Controller:
angular.module('customersApp')
.controller('customersController', ['$scope', 'dataFactory', function ($scope, dataFactory) {
$scope.status;
dataFactory.updateCustomer(cust)
.success(function () {
$scope.status = 'Updated Customer! Refreshing customer list.';
})
.error(function (error) {
$scope.status = 'Unable to update customer: ' + error.message;
});
}
Factory:
angular.module('customersApp')
.factory('dataFactory', ['$http', function($http) {
var urlBase = '/api/customers';
dataFactory.updateCustomer = function (cust) {
return $http.put(urlBase + '/' + cust.ID, cust)
};
}
Hope that solve your problem.
You can call the function directly on the TaskFactory that you pass into the controller as a dependency.
I've cleaned up your code a bit and created a plunk for you here:
And here's the code:
Controller
(function(angular) {
// Initialise our app
angular.module('myApp', [])
.controller('TaskController', function($scope, TaskFactory) {
// Initialise our variables
$scope.todos = [];
$scope.formTodoText = '';
$scope.addTodo = function() {
// Add an object to our array with a 'text' property
$scope.todos.push({
text: $scope.formTodoText
});
// Clear the input
$scope.formTodoText = '';
// Call function to send all tasks to our endpoint
$scope.sendTodos = function(){
TaskFactory.sendTasks($scope.todos);
}
};
});
})(angular);
Factory
(function(angular) {
angular.module('myApp')
.factory('TaskFactory', function($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log('data: ' + data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTasks: sendTasks
}
});
})(angular);

$scope is undefined inside $http call

My angular code
angular.module('MyApp').
controller('ProductController', function ($scope, DropDownService) {
$scope.Product = {};
$scope.ProductCategoryList = null;
DropDownService.GetCategory().then(function (d)
{
$scope.ProductCategoryList = d.data;
});
}).
factory('DropDownService', function ($http) {
var fac = {};
fac.GetCategory = function() {
return $http.get('/Product/GetAllCategory');
};
return fac;
});
my server side
public JsonResult GetAllCategory()
{
//List<tblCategory> categories = new List<tblCategory>();
try
{
using(CurtainHomesDBEntities dc = new CurtainHomesDBEntities())
{
var categories = dc.tblCategory.Select(a => new { a.Id, a.CatagoryName }).ToList();
return Json(new { data = categories, success = true }, JsonRequestBehavior.AllowGet);
}
}
catch(Exception ex)
{
return Json(ex);
}
}
I did same way many times. but throwing js error ReferenceError: $scope is not defined when assigning value to $scope.ProductCategoryList after $http request. What is the problem here? I tried many way but couldn't find out.
Even I tried in this way
angular.module('MyApp').
controller('ProductController', function ($scope, $http) {
$scope.Product = {};
$scope.LoadCategory = function () {
$scope.categoryList = null;
$http.get('/Product/GetAllCategory/')
.success(function (data) {
$scope.categoryList = data.data;
})
.error(function (XMLHttpRequest, textStatus, errorThrown) {
toastr.error(XMLHttpRequest + ": " + textStatus + ": " + errorThrown, 'Error!!!');
})
};
});
Same problem. $scope is not defined
You need to inject $scope as well as your service
angularModule.controller("ProductController", ["$scope","$http", 'DropDownService', function ($scope, $http, DropDownService) {
$scope.Product = {};
$scope.ProductCategoryList = null;
DropDownService.GetCategory().then(function (d)
{
$scope.ProductCategoryList = d.data;
});
}]);
Inject the service in your controller,
angularModule.controller("ProductController", ['$scope','$http', 'DropDownService', function ($scope, $http, DropDownService) {
$scope.Product = {};
$scope.ProductCategoryList = null;
DropDownService.GetCategory().then(function (d)
{
$scope.ProductCategoryList = d.data;
});
})

refresh button not working in Angular

I want to have a button that refresh a page (request to http to load data) :
http://plnkr.co/edit/Ol6iEoLp037ZHu0P40Wr?p=preview
refresh button with Factory - - not working
$scope.doRefresh = function() {
Content.content.success(function(data){
$scope.data = data.artists;
console.log($scope.data);
$scope.$broadcast('scroll.refreshComplete');
});
Now when you delete some data and want to have theme back you should hit refresh button but it's not working .
working demo
http://plnkr.co/edit/WHSEPxyQDi3YNkEP8irL?p=preview
$scope.doRefresh = function() {
$http.get("data.json")
.success(function(data) {
$scope.data = data.artists;
console.log($scope.data);
$scope.$broadcast('scroll.refreshComplete');
})
}
now it's working with $http
I want to do it with factory , but i can't handle this , Any advice ?
Update *****
Factory
app.factory('Content', function ($http) {
return {
content: $http.get('data.json')
}
})
You've got to tell your service to retrieve the data every time the content is requested.
app.factory('Content', function ($http, $q) {
return {
getContent: function() {
var deferred = $q.defer();
$http.get('data.json').succes(function(data) {
deferred.resolve(data);
});
return deferred.promise;
}
}
})
Then in your controller you can do:
$scope.doRefresh = function() {
Content.getContent().then(function(data) {
$scope.data = data.artists;
console.log($scope.data);
$scope.$broadcast('scroll.refreshComplete');
});
You can also just cache the data in your factory and return it without doing a request:
app.factory('Content', function($http, $q, $timeout) {
var originalData;
return {
getContent: function() {
var deferred = $q.defer();
if (!originalData) {
$http.get('data.json').succes(function(data) {
originalData = data;
deferred.resolve(data);
});
} else {
/// gonna use timeout to simulate async behaviour -- kinda hacky but it makes for a pretty interface
$timeout(function() {
defered.resolve(originalData);
}, 0);
}
return deferred.promise;
}
}
})
Careful though, changes done to the returned object will affect the originalData object.
app.factory('Content', function ($http) {
function getContent(onSuccess) {
$http.get('data.json').success(function (data) {
if (onSuccess) {
onSuccess(data)
}
}
}
return {
content: getContent
}
})
in your controller:
$scope.doRefresh = function () {
Content.content(function (data) {
$scope.data = data.artists;
console.log($scope.data);
$scope.$broadcast('scroll.refreshComplete');
});
};

Categories

Resources