Passing object from Node/Express Router to AngularJS Controller - angularjs

I have the following:
Node/Express router:
var City = require('./models/city');
module.exports = function(app) {
app.get('/cities/:zip', function(req, res) {
console.log(req.params.zip);
var query = City.find({"zip" : req.params.zip})
query.exec(function(err, city) {
if (err)
res.send(err);
console.log(city);
res.json(city);
});
});
app.get('*', function(req, res) {
res.sendfile('./public/views/index.html'); // load our public/index.html file
});
};
Angular Service:
angular.module('CityService', []).factory('City', ['$http', function($http) {
return {
get : function(zip) {
var zip = zip.zip
return $http.get('/cities/' + zip);
}
}
}]);
Angular Controller:
angular.module('CityCtrl', []).controller('CityController', ['$scope', '$http', 'City', function($scope, $http, City){
$scope.update = function (zip) {
$scope.weather = City.get({zip : zip});
if(zip.length = 5){
$http.jsonp('http://api.openweathermap.org/data/2.5/weather?zip='+ zip +',us&callback=JSON_CALLBACK').success(function(data){
$scope.data=data;
console.log(data.name);
});
}
}
}]);
Everything seems to be working fine. However, when I try to log the $scope.weather I get the entire header. I've tried logging $scope.weather.name (I know it's there) and then it returns "undefined". When I check what the server is logging it appears to log the correct JSON response. Any idea of how to get the "name" field of the returned document?

Replace $scope.weather = City.get({zip : zip}); to City.get({zip : zip}).then(function(response){$scope.weather= response.data});
As we know $http return a promise object so you must have to resolve it. you are not resolving it in service so you have to set $scope.weather in then.

Related

Angular communication with back-end

I'm trying to create an authentication-service in angular in order to register/login users.
After registering a new user I have some trouble receiving the response to the service.
Here is the flow:
Front-end controller that passes the new user to the Auth-service:
vm.onSubmit = function () {
Authentication
.register(vm.credentials)
.then(function(){
$location.path('/');
});
};
The Authentication-services register-function
register: function(user) {
return $http.post('/api/register', user).success(function(data){
console.log('authserviceDONE'); //I never get back here...
});
},
The api/register -route
app.post('/api/register', function(req, res) {
User.register(new User({ username: req.body.username}), req.body.password, function(err,user) {
if (err) {
return res.json(err);
}
passport.authenticate('local')(req, res, function () {
console.log(req.user); // User gets logged
return req.user;
});
});
});
I am hoping to receive the user-object in the front-end in order to log him in to the app but the Auth-service never receives anything. Any tips on what I might be missing here?
I do not know how your project is structured so I am going to show you what works for me. I usually have three files: app.js controllers.js services.js - this is pretty standard.
Here is an example:
app.js
angular.module('myApp', ['myApp.controllers', 'myApp.services'])
.config(function (...) { ...
controllers.js
angular.module('myApp.controllers', [])
.controller('myCtrl',function($scope, srvAccount, $log){
srvAccount.getaccount()
.then(
function(response){
$scope.account = response.data;
$log.info(response.data);
},
function(rejection){
$log.error("getaccount error");
$log.log(rejection);
}
);
...
and finally services.js
angular.module('myApp.services', [])
.factory('srvAccount', function ($http) {
return {
getaccount: function () {
return $http({
method: 'GET',
url: 'api/getaccount'
});
}
}
});
Have the browser developer tools > console open and use AngularJS $log to debug. More on $log here https://docs.angularjs.org/api/ng/service/$log

Running factory based on condition

I have a log in screen that when the user enters the correct credentials will be able to get JSON data. For now I don't have a real API link. I'm just using dummy JSON data from a script file. The loginCtrl will pass parameters to the 'dummydata' factory which will make a 'GET' request. On success, the factor will pass the JSON data to the 'useData' function in the factory. This function in the factory is what all the controllers in my ng-view use.
The problem that I am having is that all the other controllers are calling 'dummyData.dashboardsData' and getting undefined because no one has logged in to pass data to that function. How can I prevent controllers (for example, navCtrl) from calling the factory until someone has logged in?
This is my index file:
<body ng-app="ciscoImaDashboardApp" ng-style="{'background-image': backgroundImg}" ng-controller="loginCtrl">
<login></login>
<div ng-view></div>
<menu></menu>
</body>
This is my factory:
angular.module('ciscoImaDashboardApp').factory('dummyData', ['$q', '$http', function($q, $http) {
var apiServices = {};
apiServices.login = function(user,password,callback) {
$http({method: 'GET', url: 'scripts/services/dummydata.js'})
.success(function (response) {
dataStatus = response.success;
apiServices.useData(response);
callback(dataStatus);
})
.error(function(error) {
console.log("There was an error: " + error);
});
};
apiServices.useData = function(response) {
var data = response.data;
apiServices.dashboardsData = data;
}
return apiServices;
}]);
This is my navCtrl:
angular.module('ciscoImaDashboardApp')
.controller('navCtrl', function($scope, navService, $location, dummyData) {
var data = dummyData.dashboardsData;
});
This is my loginCtrl:
angular.module('ciscoImaDashboardApp')
.controller('loginCtrl', function ($scope, $rootScope, dummyData, $location) {
$scope.login = function() {
var user_email = $scope.email;
var user_password = $scope.password;
dummyData.login(user_email, user_password, function (dataStatus) {
if (dataStatus) {
console.log("Success!");
$scope.loggedIn = true;
$location.path('/welcome');
} else {
console.log("Error");
}
});
}
});

Pass URL path into $http get url- AngularJS

I'm trying to get a value from a URL part, into my $http getURL request. I have tried a few solutions (such as HTML5mode) but have not had success.
Here is my code:
angular.module('myapp123.products', [])
.factory('productsApi', ['$http', '$location',
function($http, $location){
var BASE_URL = 'http://stashdapp-t51va1o0.cloudapp.net/api/item/';
return {
get: getApiData
};
function getData() {
var product_id = $location.path().split("/")[3] || "Unknown"; //URL = /#/product/id/1234 <---
return $http.get(BASE_URL + product_id);
}
}]
)
.controller('productsCtrl', ['$scope', '$log', 'productsApi', 'UserService',
function($scope, $log, productsApi, UserService) {
$scope.isVisible = function(name){
return true;// return false to hide this artist's albums
};
// <====== Rewrite with accounts preferences
productsApi.getApiData()
.then(function (result) {
//console.log(JSON.stringify(result.data)) //Shows log of API incoming
$scope.products = result.data;
})
.catch(function (err) {
$log.error(err);
});
}
]);
The code in your example has a lot of syntax errors in it. Here is what it should look like, based on what I think you are going for...
angular.module('myapp123.products', [])
.config(locationConfig)
.factory('productsApi', productsApiFactory)
;
locationConfig.$inject = ['$locationProvider'];
function locationConfig($locationProvider) {
$locationProvider.html5Mode(true);
}
productsApiFactory.$inject = ['$http', '$location'];
function productsApiFactory($http, $location) {
var BASE_URL = 'http://stashdapp-t51va1o0.cloudapp.net/api/list/';
return {
get: getData
};
function getData() {
var product_id = $location.path().split("/")[3] || "Unknown";
return $http.get(BASE_URL + product_id);
}
}
In this version, the config function is correctly defined to set up html5mode and the service factory is configured to use $location each time the get() method is called.
You would use the service in a controller like this:
ExampleController.$inject = ['productsApi'];
function ExampleController(productsApi) {
productsApi.get()
.then(function onSuccess(res) {
// handle successful API call
})
.catch(function onError(err) {
// handle failed API call
})
;
}

ionic http.get doesn't work in factory

So i can get data from a URL if i do it from with in my controller. But if i take that and move it into a factory it doesn't work. So what am i doing wrong?
angular.module('starter.notifications', [])
.factory('Notifications', function($http) {
var link = "http://localhost:8000/notifications";
var notifications = [];
return {
getAll: function()
{
return $http.get(link).success(function(data, status, headers, config) {
notifications = data;
return notifications;
});
},
This code works if i move it into a controller, but why doesn't it work in a factory?
This is how i did it.
In the top of your app.js
angular.module('app', ['ionic', 'app.controllers', 'app.services','ngCordova'])
Let ionic knows you have an services.js by declaring it.
services.js (an http post request example)
angular.module('app.services', ['ngCordova'])
.factory('dataFactory', function($http, $cordovaGeolocation){
var dataFactory = {};
dataFactory.login = function(username, password){
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
var data = 'userID=' + username + '&password=' + password +'';
var httpAddressDoLogin = "http://YOURURL";
return $http.post(httpAddressDoLogin, data, config);
};
return dataFactory;
})
In your controller:
dataFactory.login(username, password).then(function(resp) {
Hope that helps.
On services.js $http.get resulting promise not object array. To make it work write like this on your services.js
angular.module('starter.services', [])
.factory('Actor', function($http) {
var actors = $http.get('http://ringkes/slim/snippets/actor').then(function(resp) {
if (resp) {
return = resp['data'];// This will produce promise, not array so can't call directly
} else {
console.error('ERR', err);
}
});
return {
all: function() {
return actors;
}
};
});
then call it on controller like this:
controller('DashCtrl', function($scope,Actor,$http) {
Actor.all().then(function(actors){ $scope.actors = Actor.all();
});
});

angular phonegap - my factory not delivering data

I am trying to create a Phonegap App. I use Angular as frontend.
I have a factory that gets data from an external ressource. In .config i added the access origin * attribute.
When I debug using http://debug.build.phonegap.com it seem to returning the data. The call to the API is returning 584 bytes.
So there seems to be an issue regaring the data from the factory to the frontend.
My Factory
.factory('ActivityService', ['$http', '$location', 'CookieService', function ($http, $location, CookieService) {
return {
getActivitiesService: function (data) {
$http.post('http://www.example.com/api/v1/Activity.php',
{
MethodName: "getActivitiesService",
SessionToken: CookieService.getCookie("ua_session_token")
})
.success(data)
},
postActivityService: function (activity) {
$http.post('http://www.example.com/api/v1/Activity.php',
{
MethodName: "postActivityService",
SessionToken: CookieService.getCookie("ua_session_token"),
ActivityName: activity.activityName,
ActivityDescription: activity.activityDescription
}).success(function () {
$location.path("/home");
});
}
}
}])
My controller
.controller('HomeCtrl', ['$scope', 'ActivityService', function($scope, ActivityService) {
//GET activities from server / DB
ActivityService.getActivitiesService(function (data) {
if (jQuery.isEmptyObject(data))
{
$scope.emptyJsonArray = "No activities.";
}
else
{
$scope.$apply(function () { $scope.activities = data; });
}
})
}])
In my app.js i do this:
//Manually bootstrapping Angular, after cordova.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
angular.element(document).ready(function () {
angular.bootstrap(document, ['attenttoApp']);
});
};
Update:
Thanks both of you. I checked the content of the returned data, and it was an error that was returned.
Fixed it and now i works...
in the doc, they use return in factory
https://docs.angularjs.org/api/ng/service/$http
so try it like this
getActivitiesService: function (data) {
var toreturn = $http.post('http://www.example.com/api/v1/Activity.php',
{
MethodName: "getActivitiesService",
SessionToken: CookieService.getCookie("ua_session_token")
})
.success(function(data, status, headers, config) {
return data;
})
return toreturn;
},
and i think you should see in direction of promises, i wrote an answer about this, look at it
For which status codes promise resolving

Resources