req.params.value is undefined - angularjs

In my Node js Application, am using Angular js for data binding.
Am using ng-controller, inside which I use an http service to get data from the database.
On the button click event am calling clickedbutton function,where I pass a value to the service.
HomeController.js
app.controller('BasicHomeController', function ($scope, $filter,$http) {
$scope.clickedbutton=function(value){
$http.get('/getData/'+value)
.then(successCallback, errorCallback);
};
);
However am not able to get the service value from the browser using req.params. It gives undefined value.
app.js
app.get('/getData/:value', function(req,res){
var reqid = req.params.value; //It gives reqid as undefined
});

Related

angular to fetch the json service from http

I have my js for angular to fetch the json service from http and am using the {{post.title}} on my html to get the data and post to my html.
The data is not showing up on html page - using code pen.
var app = angular.module("blogApp", []);
app.controller("mainCtrl", function($scope) {
$scope.posts = [];
let postsUrl ="https://jsonplaceholder.typicode.com/posts"
getPosts().then(posts =>{
$scope.posts = posts.slice(3);
$scope.$apply();
});
function getPosts(){
return fetch(postsUrl).then(res=>res.json());
}
});
I have seen your shared codepen. So Ricky as you are new to angularJS, I would suggest you to read the documentation related to angular 1 from here: Angular JS - Documentation
Now coming to your requirement, you required to call an external API and use the data from the result. For that you have to learn about the $http in angularJS : $http documentation
Coming to the code, angular supports the dependency injection. The code you have shared is a mystery for me like what fetch(postsUrl) function is doing? Where is the declaration?
Cut and short, the implementation should be clear and readable. Here is my refactored one:
var app = angular.module("blogApp", []); //here you defined the ng-app module
//you are initializing a controller, you need to inject $http for calling the API
app.controller("mainCtrl", function($scope, $http) {
//Declaration of the posts object
$scope.posts = [];
//Onetime initialization of the API Endpoint URL
let postsUrl ="https://jsonplaceholder.typicode.com/posts";
//A method for getting the posts
function getPosts(){
//We are calling API endpoint via GET request and waiting for the result which is a promise
//todo: Read about the Promises
//A promise return 2 things either a success or a failure callback, you need to handle both.
//The first one is success and the second one is a failure callback
//So in general the structure is as $http.get(...).then(successCallback, failureCallback)
$http.get(postsUrl).then(function(response){
//In promises you get data in the property data, for a test you can log response like console.log(response)
var data = response.data;
$scope.posts = data; //Storing the data in the posts variable
//Note: you don't need to call the $scope.$apply() because your request is with in the angular digest process.
//All the request which are outside the angular scope required a $apply()
}, function(err){
//log the err response here or show the notification you want to do
});
}
//The final step is to call that function and it is simple
getPosts();
});
Coming to the second part to show the data. You have to use the ng-repeat documentation, it is as ng-repeat="var item in collection track by $index". It's documentation is here ng-repeat
So you html should be in this structure:
<div ng-repeat="var post in posts track by $index">
{{post.userid}}
{{post.id}}
{{post.title}}
{{post.body}}
</div>
Now it is onto you to learn and implement.

Passing a parameter to a $resource?

I have a controller that that looks like this:
(function() {
angular
.module("main")
.controller("HomeCtrl",
["branchResource",
"adalAuthenticationService",
HomeCtrl]);
function HomeCtrl(branchResource, adalService){
var vm = this;
vm.copyrightDate = new Date();
vm.user = adalService.userInfo.userName;
// right here, can I insert the vm.user from above
// as a parameter to the resource's query?
branchResource.query(function (data) {
vm.branches = data;
});
}}());
The user is authenticated by the time they reach this point in the app. So, the user's info is available.
I have a backend API that takes a user's name and returns the names of branches that user is authorized to. I can paste the URL into my browser, along with a valid user name, and get expected results. I'm trying to use that API in my branchResource:
(function () {
"use strict";
angular
.module("common.services")
.factory("branchResource",
["$resource", branchResource]);
function branchResource($resource){
return $resource("/api/user/GetAllUserBranches?federatedUserName=:user")
}}());
My problem, though, is that I don't know how to pass the vm.user to the branchResource from the controller. Can someone point me in the right direction?
Create the $resource object with:
function branchResource($resource){
̶r̶e̶t̶u̶r̶n̶ ̶$̶r̶e̶s̶o̶u̶r̶c̶e̶(̶"̶/̶a̶p̶i̶/̶u̶s̶e̶r̶/̶G̶e̶t̶A̶l̶l̶U̶s̶e̶r̶B̶r̶a̶n̶c̶h̶e̶s̶?̶f̶e̶d̶e̶r̶a̶t̶e̶d̶U̶s̶e̶r̶N̶a̶m̶e̶=̶:̶u̶s̶e̶r̶"̶)̶ ̶
return $resource("/api/user/GetAllUserBranches")
}}
Call the $resource object with:
branchResource.query({"federatedUserName": vm.user}, function (data) {
vm.branches = data;
});
//OR
vm.branches = branchResource.query({"federatedUserName": vm.user});
It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.
Each key value in the parameter object is first bound to url template if present and then any excess keys are appended to the url search query after the ?.
For more information, see AngularJS ngResource $resource API Reference.

Fetch an external json file through Angular JS

I am trying to implement a faceted search based on AngularJS https://github.com/kmaida/angular-faceted-search
As the example is based on a dataset incorporated in the JS, I am trying to load the JSON File remotely. (total noob in angularJS by the way).
In the example, the Controller is defiend as:
myApp.controller('MainCtrl', function($scope, Helpers) {
And there are 2 helpers defined
myApp.factory('Helpers', function() {...
I am trying to inject the $http in a third helper, my code:
,
//below line 30 in https://github.com/kmaida/angular-faceted-search/blob/master/app.js
fetchData: function (){
var resultjson=[]
$http.get('/api/data.json').success(function(data) {
resultjson=data
console.log(data);
});
console.log(resultjson);
return resultjson;
}
The newly defined variable resultjson has a value in the success function, but no value beyond that point.
Any one can help me fetch the data correctly? Appreciate the support.
If you want to receive data from $http, you will have to use promises. Right now, you are returning resultjson before the value has been received from the api end point.
You should return promise, and once the promise is resolved, the value will be in the promise.
Due to the fact, that $http returns promise, you can return it directly, without wrapping it in another promise.
fetchData: function (){
return $http.get('/api/data.json');
}
and you can access the data in your your controller and assign to the scope:
Helpers.fetchData().then(function(data){
$scope.items = data.data;
})

Cannot access Firebase object attributes. Value displayed as undefined ANGULARFIRE

I want to do a custom login for a demo of my doing, but I encountered a problem.
I use the username to access a reference url inside Firebase, I get a returned object. If I want to access a single attribute, I get the undefined value, but if I add in my html {{returnedObj.name}} the value is displayed.
Why is that?
angular.module('Demo').controller('loginCtrl', ['$scope', '$firebase', '$location', function($scope, $firebase, $location){
$scope.user = {};
$scope.check = function(){
console.log('https://fabritzio-demo.firebaseio.com/users/' + $scope.user.name);
$scope.returnedObj = $firebase(new Firebase('https://fabritzio-demo.firebaseio.com/usuarios/' + $scope.user.name)).$asObject();
alert($scope.returnedObj.name); // returns undefined value
};
}]);
Firebase values are loaded asynchronously. The value will not yet have been loaded into $scope.returnedObj when the alert fires.
There are a couple of ways to handle values loading asynchronously from Firebase, for example using $loaded to get a promise:
$scope.returnedObj.$loaded().then(function () {
alert($scope.returnedObj.name);
});
The value is displayed in the template because Angular watches all $scope variables for changes. When the value is loaded (milliseconds later), it is immediately displayed.

AngularJS : Service data binding

I am trying to call a service in angular.js through a controller on load and return a promise. I then expect the promise to be fulfilled and for the DOM to be updated. This is not what happens. To be clear, I am not getting an error. The code is as follows.
app.controller('TutorialController', function ($scope, tutorialService) {
init();
function init() {
$scope.tutorials = tutorialService.getTutorials();
}
});
<div data-ng-repeat="tutorial in tutorials | orderBy:'title'">
<div>{{tutorial.tutorialId}}+' - '+{{tutorial.title + ' - ' + tutorial.description}}</div>
</div>
var url = "http://localhost:8080/tutorial-service/tutorials";
app.service('tutorialService', function ($http, $q) {
this.getTutorials = function () {
var list;
var deffered = $q.defer();
$http({
url:url,
method:'GET'
})
.then(function(data){
list = data.data;
deffered.resolve(list);
console.log(list[0]);
console.log(list[1]);
console.log(list[2]);
});
return deffered.promise;
};
});
Inside of the ".then()" function in the service, I log the results and I am getting what I expected there, it just never updates the DOM. Any and all help would be appreciated.
getTutorials returns promise by itself. So you have to do then() again.
tutorialService.getTutorials().then(function(data){
$scope.tutorials = data;
});
Before that, $http returns a promise with success() and error().
Although you can also use then as well
Since the returned value of calling the $http function is a promise,
you can also use the then method to register callbacks, and these
callbacks will receive a single argument – an object representing the
response.
So you are correct with that.
What is your data coming from the http call look like? Your code works - I created a version of it here http://jsfiddle.net/Cq5sm/ using $timeout.
So if your list looks like:
[{ tutorialId: '1',
title : 'the title',
description: 'the description'
}]
it should work
In newer Angular versions (I think v 1.2 RC3+) you have to configure angular to get the unwrap feature working (DEMO):
var app = angular.module('myapp', []).config(function ($parseProvider) {
$parseProvider.unwrapPromises(true);
});
This allows you to directly assign the promise to the ng-repeat collection.
$scope.tutorials = tutorialService.getTutorials();
Beside that I personally prefer to do the wrapping manually:
tutorialService.getTutorials().then(function(tutorials){
$scope.tutorials = tutorials;
});
I don't know the exact reason why they removed that feature from the default config but it looks like the angular developers prefer the second option too.

Resources