I have to call a restful API with basic auth "i think the auth is working)"
that needs this special custom header: "X-AppGlu-Environment: staging" I don't know how to put the header" then I need to post to one URL, data with this format:
Body:
{
"params": {
"stopName": "what you want search"
}
}
Let's see my code at moment "it's not structured yet"
controller:
'use strict';
angular.module('myApp', ['base64'])
.controller('transportController', function($scope, $http, $base64){
$scope.$watch('search', function() {
fetch();
});
function fetch(){
var data = {
"params": {
"stopName": $scope.search
}
}
$http.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
var encoded = $base64.encode("xxxx:xxxx");
$http.defaults.headers.common.Authorization = 'Basic ' + encoded;
$http.post("the url", data)
.then(function(response){ $scope.details = response.data; });
}
});
view:
<div class="input-group search-bar">
<input type="text" ng-model="search" ng-model-options="{ debounce: 800 }" onclick="select()" class="form-control" placeholder="Enter destiny" autofocus />
<span class="input-group-addon bar-style"><i class="glyphicon glyphicon-search"></i></span>
I receive a error 400 bad request when i try to search for something, i think is something with the format of the object i'm trying to send, but if is, i don't know what to change.
Is working now i changed to this structure
function fetch(){
var data = {
"params":{
"stopName": "%"+$scope.search+"%"
}
}
var encoded = $base64.encode("xxxx:xxxx");
$http({
url: "url",
headers : {
"X-AppGlu-Environment":"staging",
"Authorization": "Basic "+encoded,
"Content-Type" : "application/json; charset=utf-8"
},
method: 'POST',
data: {
"params":{
"stopName": "%"+$scope.search+"%"
}
}
}).then(function(response){
$scope.details = response.data.rows;
});
// $http.get("http://www.omdbapi.com/?s=" + $scope.search)
//.then(function(response){ $scope.related = response.data; });
}
Related
I am new in Angular and trying to POST data , but I am getting undefined status. My JSON raw body is like this :
{
"Name": "Something",
"Description": "Something",
"Data": []
}
Name and description is from user input field and Data will be used later to push another JSON object in the array.
I tried but not getting exact output.
Controller:-
app.controller('postController', ['$scope', '$http', 'appService', function ($scope, $http, AppService) {
$scope.addInfos = [{
Name: $scope.name,
Description: $scope.description,
Data: []
}];
$scope.Create = function () {
$scope.addInfos.push({
'Name': $scope.Name,
'description': $scope.Description,
'Data': []
});
$scope.dataObj = {
Name: $scope.name,
Description: $scope.description,
Data: []
};
$http({
method: 'POST',
url: 'http://192.120.27.8:2000/api/Add',
data: $scope.dataObj
}).then(function (data, status, headers, config) {
alert("success");
console.log(data + $scope.Name + $scope.Description);
}, function (data, status, headers, config) {
alert("error");
});
$scope.name = '';
$scope.Description = '';
};
HTML page :-
<div class="input-group col-md-10">
<span class="input-group-addon" id="reg_input" >Name</span>
<input type="text" class="form-control" placeholder="" ng-model="addInfos.name">
</div>
<div class="input-group sepH_b col-md-10">
<span class="input-group-addon" id="reg_input" >Description</span>
<textarea name="reg_textarea" id="reg_textarea" cols="10" rows="3" class="form-control" ng-model="addInfos.description"></textarea>
</div>
<div class="col-md-4">
<a style="" class="btn btn-md btn-primary" ng-click="Create(addInfos)">Create</a>
</div>
The output which I can see in my console is [object Object]. What mistake am I doing here ?
NOTE:- Here I didn't mentioned Data: field as it will be predefined array as of now like this {data:[]} need to inject and pass Name and Description in JSON as I mentioned above.
SECOND also I need to push this over all output data to the Service to store for further use.
Thanks guys , now I can able push necessary datas inside the JSON I did second work around .
$scope.addInfos = {Data: []};
$scope.Create = function() {
$http({
method : 'POST',
url : 'http://192.120.27.8:2000/api/Add',
data : $scope.addInfos
}).success(function(data, status, headers, config) {
growl.success("Created a new File");
console.log(data);
},function (data, status, headers, config) {
growl.error("Something is wrong");
});
};
My second concern is still there , now how to push these data to a service. var something =[];?
My app goes into infinite loop while firing $http get method inside a function
In my controller I am using POST and getting data from API after authorization and displaying it.
var app = angular.module('myApp', []);
app.controller('ctrl1', function($scope, $http) {
$http({
url: 'url',
method: "POST",
data: 'postData',
headers: {
'Authorization': 'value'
}
})
.then(function(response) {
$scope.hotels = response.data;
});
$scope.imagePath = function(id) {
console.info(id);
if (id) {
$http({
method: 'GET',
url: 'url=' + id
})
.then(function(response) {
var imgdata = response.data;
console.info(imgdata);
var imgdata1 = imgdata.data.image_name;
return "url" + imgdata1;
});
}
};
});
In my img ng-src I have to call data from another API from the key exterior_image which I am passing in my function but it goes into an infinite loop. Also I know I have to use angular forEach in imgdata1.
<div ng-controller='ctrl1'>
<select ng-options='item as item.hotel_name for item in hotels.data' ng-model='hotel'></select>
<h1>{{hotel.hotel_name}}</h1>
<p>{{hotel.hotel_description}}</p>
<img ng-src="{{imagePath(hotel.exterior_image)}}">
</div>
Try this in your Controller:
var app = angular.module('myApp', []);
app.controller('ctrl1', function ($scope, $http) {
$scope.current_Hotel = {
hotel_name: "Default Value Here",
hotel_description: "Default Value Here",
exterior_image: "Default id here",
image_url: "Default url here"
};
$http({
url: 'url',
method: "POST",
data: 'postData',
headers: {
'Authorization': 'value'
}
}).then(function (response) {
$scope.hotels = response.data;
});
$scope.selectHotel = function () {
$http({
method: 'GET',
url: 'url=' + $scope.current_Hotel.exterior_image
}).then(function (response) {
var imgdata = response.data;
var imgdata1 = imgdata.data.image_name;
$scope.current_Hotel.image_url = "url" + imgdata1;
});
};
});
and this:
<div ng-controller='ctrl1'>
<select ng-options='item as item.hotel_name for item in hotels.data' ng-model='current_Hotel'></select>
<h1>{{current_Hotel.hotel_name}}</h1>
<p>{{current_Hotel.hotel_description}}</p>
<img ng-src="{{current_Hotel.image_url}}">
</div>
I am trying to send data from my Angular.js controller to Node.js backend. I succeeded in making a MongoDB entry when the request is raised.But the data is missing in the MongoDB entry. I am stuck and can't proceed with my app anymore. Can anyone give me a clear explanation why I am not able to send the form data to the Node.js.
I had put my schema of the data here:
var common = require('../common');
var inviteeSchema = common.Schema({
email: String
});
var Invite = common.conn.model('Invite', inviteeSchema);
module.exports = Invite;
I have enclosed the routing code here.
router.route('/addtoinvitelist').post(function (req, res, next) {
var invite =new Invite(req.body);
invite.save(function(err,email){
if(err) throw err;
res.json({message:"your mail id is stored in our database we will soon send you an invite"})
});
});
My HTML form goes here
<form action="#">
<div class="form-group">
<label for="subcribeNewsletter" class="control-label">INVITE FORM<br> <small>We are happy to invite you to medicoshere, So please enter your email ID in the below form.</small></label>
<div class="input-group input-group-in input-group-sm">
<div class="input-group-addon"><i class="fa fa-envelope text-belpet"></i></div>
<input class="form-control" id="subcribeNewsletter" placeholder="name#mail.com" ng-model="useremail" required>
<div class="input-group-btn">
<button type="submit" class="btn btn-default text-belpet" ng-click="AddToInviteList(useremail)"><strong>OK</strong></button>
</div>
</div>
</div><!-- /.form-group -->
</form><!-- /form -->
my angular service functions goes here
`this.AddToInviteList = function (email, cb) {
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}, // set the headers so angular passing info as form data (not request payload)
data:"email"
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
}`
Controller function is here
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.email = {};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}
});
Pass email as json object { 'email' : email }.
Just try this code:
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data:{ 'email' : email }
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
Controller :
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.AddToInviteList = function () {
$scope.user = {
email : $scope.useremail
};
UserServices.AddToInviteList($scope.user, function (dataresponse) {
console.log(dataresponse);
})
}
});
In server side you can access the email by calling 'req.body.email'
Change your model name in HTML input element with email and send request as
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/json'
},
data:{ 'email' : email }
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
and get it at backend side as
req.body.email
I think that should work!
Update
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}
.controller('LoginConnect', ['$scope', 'connecting',
function(connecting, $scope){
$scope.user = {};
var inputLogin = $scope.user.login;
var inputPassword = $scope.user.password;
$scope.connect = function (){
connecting(ConnectingFactory);
};
}
])
.factory('connecting', ['$http','$q', function ($http,$q,inputLogin, inputPassword, ConnectingFactory){
var ConnectingFactory = {};
console.log(ConnectingFactory);
ConnectingFactory.login = function(){
var deferred = $q.defer();
$http({
method: 'POST',
url: "http://api.tiime-ae.fr/0.1/request/login.php",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {login: inputLogin, password: inputPassword}
})
.success(function(result){
deferred.resolve(result);
var promise = deferred.promise;
promise.then(function(result){
console.log(result);
// jsonTab = angular.fromJson(result);
// $scope.result = result["data"];
// $scope.user.token = result["data"];
});
})
};
return ConnectingFactory;
}]);
;
And here the HTML :
<!-- User Connection -->
<form name="userConnect" ng-submit="connect()" novalidate ng-controller="LoginConnect">
<label>
Enter your name:
<input type="text"
name="myEmail"
ng-model="user.login"
/>
</label>
<label>
Enter your Password:
<input type="password"
name="password"
ng-model="user.password"
/>
</label>
<input type="submit" value="Connection">
<p>resultat : {{result}}</p>
<p ng-model="user.token">
token : {{mytoken}}
</p>
<p ng-model="user.datab">
datas : {{datab}}
</p>
<br><br><br>
</form>
Hi, I m new in Angular Js developpement, i have no error but not any data in sent to the API. I think their is no link between my function "connect()" and the factory. Could you help me pls ?
Don't use the success method either way.Both methods have been deprecated.
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
Here is the shortcut method
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
Here is a longer GET method sample
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Official Documentation
Regarding the factory , call it correctly as ConnectingFactory.login().
Also, the order here is incorrect, as pointed out by Harry.
['$scope', 'connecting',
function(connecting, $scope){
I have what would seem to be a simple problem with AngularJS - apologies if so. I'm new and have searched all over and can't quite find an answer to what I want to do.
Basically I have a $http request that is getting a list of 'Cards' from a server which I'm then using ng-repeat to build in the HTML. I then want to populate those Cards with a number of 'Metrics' - also retrieved from the server. I have a controller for the 'Cards' (parents) and a separate controller for the 'Metrics' (children).
My issue is that I can't work out how to reference the ID of the parent 'Card' when making the child $http request.
Below is the HTML & JS that I am using - any help would be appriciated:
HTML:
<div class="Dashboard container-fluid" ng-controller="DahsboardCardController as Dashboard">
<div ng-repeat="Card in Dashboard.DashboardCards">
<div class="DashboardCard card">
{{Card.CardDisplayName}}
<div class="DashboardCardBody" ng-controller="DahsboardMetricController as Metric">
<div ng-repeat="Metric in Metric.DashboardMetrics">
{{Metric.MetricDisplayName}}
</div>
</div>
</div>
</div>
JS:
(function () {
var app = angular.module('OtterDashboard', [ ]);
app.controller('DahsboardCardController', [ '$http', function($http) {
//Declare a varaible for the data
var DashboardCards = this;
//Set the varaiable to an empty array to receive the data
DashboardCards.DashboardCards = [ ];
$http({
//Request the data
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/tbl_Card',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
//The data was sucessfully received, populate the variable with it
DashboardCards.DashboardCards = data.data.d.results;
}, function errorCallback(response) {
//There was an error
console.log('Card data could not be retrieved');
});
}]);
app.controller('DahsboardMetricController', ['$http', function($http, Card) {
//Declare a varaible for the data
var DashboardMetrics = this;
//Set the varaiable to an empty array to receive the data
DashboardMetrics.DashboardMetrics = [ ];
$http({
//Request the data
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/DashboardMetric?Card=%27' + **???reference to parent card ID???** + '%27',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
//The data was sucessfully received, populate the variable with it
DashboardMetrics.DashboardMetrics = data.data.d.results;
}, function errorCallback(response) {
//There was an error
console.log('Metric data could not be retrieved');
});
}]);
})();
Thank you!
EDIT 1
Use a service for shared variable between controllers. Look the example:
app.controller('DahsboardCardController', ['$http', function($http, $sharedResource) {
var DashboardCards = this;
DashboardCards.DashboardCards = [ ];
$http({
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/tbl_Card',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
DashboardCards.DashboardCards = data.data.d.results;
$sharedResource.set("id", "<pass id value>");
}, function errorCallback(response) {
console.log('Card data could not be retrieved');
});
}]);
app.controller('DahsboardMetricController', ['$http', function($http, Card, $sharedResource) {
var DashboardMetrics = this;
DashboardMetrics.DashboardMetrics = [];
$http({
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/DashboardMetric?Card=%27' + $sharedResource.get("id") + '%27',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
DashboardMetrics.DashboardMetrics = data.data.d.results;
}, function errorCallback(response) {
console.log('Metric data could not be retrieved');
});
}]);
app.factory('$sharedResource', function () {
var property = {};
return {
get: function (key) {
return property[key];
},
set: function(key, value) {
property[key] = value;
}
};
});
EDIT 2
When working with angularjs is recomended use a one object for print object in table. Why this is a beautiful s2.
Look this example. To help you in development. Use the sample function pass the parentId in load(CardId). This function will run in the page load.
I too fix code html. You used the alias controller before input field of same.
var app = angular.module("App", []);
app.controller('DahsboardCardController', ['$scope', function($scope) {
$scope.DashboardCards = [{
CardId: "111",
CardDisplayName: "Card 1"
}, {
CardId: "222",
CardDisplayName: "Card 2"
}, {
CardId: "333",
CardDisplayName: "Card 3"
}];
}
]);
app.controller('DahsboardMetricController', ['$scope', function($scope) {
$scope.load = function(CardIdParent) {
console.log(CardIdParent);
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" class="Dashboard container-fluid" ng-controller="DahsboardCardController as Dashboard">
{{Dashboard.DashboardCards}}
<div ng-repeat="Card in DashboardCards">
<div class="DashboardCard card">
{{Card.CardDisplayName}}
<div class="DashboardCardBody" ng-controller="DahsboardMetricController as Metric" ng-init="load(Card.CardId)">
This a id parent: {{Card.CardId}}
<div ng-repeat="MetricItem in DashboardMetrics">
{{MetricItem.MetricDisplayName}}
</div>
</div>
</div>
</div>
</div>