Pass input to url parameters in angular 2 - javascript

I'm trying to pass an input from angular2 to a url parameter on a get request to retrieve data from my database. I've looked everywhere to see if anyone else has done this and while they have passed objects as parameters I'm not sure if that is what I need to do.
here's some code..
This is my backend express route to retrieve data from my mongodb.
app.get('/displayorders/:showOrder', function (req, res) {
db.woocommerceorders.findOne({ id: req.params.showOrders }, function
(err, data) {
if(err){
console.log(err);
}res.send(data);
});
})
This is my service in angular2 to retrieve data from my mongodb.
displayOrders(showOrders) {
var displayedOrders;
return this.http.get('http://localhost:3000/displayorders/:' + showOrders)
.map(res => res.json());
}
This is my front end click event to retrieve the desired parameter from the input and pass it as a parameter on my url string.
onFindOrderById(showOrders) {
this.woocommerceService.displayOrders(showOrders)
.subscribe(
data => this.showOrders = JSON.stringify(data),
error => alert(error),
() => console.log('Displaying Order By Id')
);
}
This is my html used to take the input and pass it to my click event function.
<div class="form-group container bottom-border">
<button type="button" class="btn displaybutton"
(click)="onFindOrderById(showOrders)">Click To Retrieve</button>
<br><br>
<div class="row">
<div class="col-xs-6">
<input class="form-control col-xs-6" [(ngModel)]="showOrders"
placeholder="Input Id Number">
<p><b>Retrieved Order:</b></p> <div>{{showOrders}}</div>
</div>
</div>
</div>
I'm wondering if I should try a post request instead? I feel as though this should be straight forward but right now I keep getting an error of UNEXPECTED END OF JSON ENDPOINT. Any help would be greatly appreciated.

Related

How can I pass data from Angular to Node.Js server and vice versa by one endpoint?

I have code in Nodejs as backend and Angular as frontend.
I want to receive and send data by one endpoint and based on that data from server toggle a button. Toggling is working now but I want when I sign out from the dashboard next time that I log in I could see the value of the key is based on the value from the database.
For example, first, it's SET after clicking it changed to CLEAR and I sign out from the dashboard. When next time I log in I want to see the CLEAR label on my button.
These are codes for several parts of the app:
Angular Service
this.setUserFeatured = function(id, setFeatured) {
return $http.put('/admin/v2/users/' + id + '/featured', { setFeatured: setFeatured })
.then(returnedDataOrError);
};
Angular Controller
function updateFeaturedButtonLabel() {
$scope.featuredButtonLabel = $scope.user.setFeatured ? "Clear Featured" : "Set Featured";
}
function toggleFeatured () {
$scope.user.setFeatured = !$scope.user.setFeatured;
UserService.setUserFeatured($stateParams.id, $scope.user.setFeatured)
updateFeaturedButtonLabel();
};
Html File
<a class="btn btn-info" ng-click="toggleFeatured()" ng-class="{on:user.setFeatured}">{{featuredButtonLabel}}</a>
Server Controller
function addFeaturedUser(req: $Request, res: $Response, next: NextFunction) {
const schema = Joi.object().keys(_.pick(validate, ['userId', 'setFeatured']));
const queryParams = { userId: req.params.id };
if (!req.params.id) {
return new errors.BadRequest('userId is not specified');
}
return validate.validate(queryParams, schema)
.then(validatedParams =>
userService5.updateUserLabel(validatedParams.userId, req.body.setFeatured))
.then(result => res.json(result))
.catch(next);
}
router.put('/users/:id/featured', addFeaturedUser);
And updateUserLabel is a function that handling the connection to the database and retrieving the data.
I just wonder how can I use the data from the server to change the label of the button?
true/false for the setting the button is coming from the .then(result => res.json(result))
Thanks in advance for help
For your question, I suppose you are asking how to use the response object returned in
$http.put().then(function(response){})
You can find the structure of response object in following document.
https://docs.angularjs.org/api/ng/service/$http
To access the data returned from server:
$http.put().then(function(response){response.data})
which corresponds to what your server sends.
Besides, the toggleFeatured function should be add to $scope object.
Otherwise, ng-click can't trigger that function in html template.
Hope it helps.

I want to submit a form and update the values from the form (Mysql result) without refreshing the whole page

as the title says, I want to submit a form and update the values from the form (Mysql result) without refreshing the whole page.
See Image 1, I want if I press the blue button that the values updated.
Can someone help me?
Thanks.
If you are willing to use newer apis like Promise and fetch, it's super easy and neat.
foo.submit.addEventListener("click", (e) => {
e.preventDefault();
fetch("YOUR_URL", {
method: 'POST',
body: new URLSearchParams({
name: foo.user_name_value,
email: foo.user_mail.value
})
}).then(response => {
return response.json() // assume returning data is in json format, otherwise .text() could be used
}).then(data => {
// deal with return data
}).catch(err => {
// deals with errors
})
})
<form name="foo">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="user_name">
</div>
<div>
<label for="mail">E-mail:</label>
<input type="email" id="mail" name="user_mail">
</div>
<div>
<button name="submit" type="submit">Send your message</button>
</div>
</form>
Older method XHR shares same idea, but requires a bit more code. You may use axios or so to simplify the process.

Angular 4 and Nodejs http post request implementation error

I created small test application using Angular 4 and Nodejs. I want to insert a text field value to the database either Mongo or mysql.
Following files I created server.js for running nodejs, Created server>router folder with another file api.js and Angular 4 user component created.
What i did code shown below
user.component.html
<form (submit)="addHobby(hobbies,hobby.value)">
<input type="text" #hobby>
<input type="submit" value="Submit">
</form>
user.component.ts
addHobby(arrHob,hobby) {
if(arrHob.indexOf(hobby) == -1) {
this.hobbies.unshift(hobby);
this.dataService.postHobby(hobby).subscribe((posts) => {
console.log(posts);
})
}
return false;
}
Services folder contain data.service.ts
postHobby(hobby) {
return this.http.post('/api/insertHobby',hobby).map(res => res.json().data);
}
server router folder contain api.js
router.post('/insertHobby', (req, res) => {
console.log("Welcome to post method");
console.log(req.body.data);
})
When form submitting i'm getting output as only welcome to post method
req.body.data i'm getting as *'Undefined'* How to resolve this issue. Any way thanks to everyone..
since you are not passing the variable as object , you need to pass it in object format as below :
postHobby(hobby) {
return this.http.post('/api/insertHobby',{hobby: hobby}).map(res => res.json().data);
}

Posting Input value as param to web service API in Angular

I have started learning Angular and I'm stuck on something that should be trivial. I'm from a Rails background and created a very simple Rails web-service that manages a MailingList. Currently 2x API endpoints exist in my web-service:
/api/v1/mailing_lists [GET]
/api/v1/mailing_lists [POST]
The POST endpoint requires a valid email as a PARAM in the API call. And this is where I'm stuck. How do I pass this param to my API in Angular? I've tried using solutions from around the web but I'm just not getting it right. Here's what I have thus far:
In my services.js:
angular.module('webFrontendApp.services', []).factory('MailingList', function($resource) {
var data = $resource(
'http://localhost:3000/api/v1/mailing_lists.json',
{},
{
// 'get': { method:'GET', cache: false},
'query': { method:'GET', cache: false, isArray:true },
'save': {method: 'POST', cache: false }
});
return data;
});
In app.js
....
.when('/list/new', {
templateUrl: 'views/list-new.html',
controller: 'MailingListCtrl'
})
....
Controller as mailinglist.js
angular.module('webFrontendApp.controllers', [])
.controller('MailingListCtrl', function($scope, MailingList) {
// Get all posts
$scope.mailing_lists = MailingList.query();
// Our form data for creating a new post with ng-model
$scope.memberData = {};
$scope.newMember = function() {
var member = new MailingList($scope.memberData);
member.$save();
};
});
The form looks like this:
<form role="form" ng-submit="newMember()">
<div class="row">
<div class="input-group">
<input type="text" ng-model="memberData.email" placeholder="New mailing list member" class="form-control">
<span class="input-group-btn">
<input type="submit" class="btn btn-primary" value="Add">
</span>
</div>
</div>
</form>
When I submit the form, nothing seems to happen, but I am receiving a 405 error response from my web service. After looking into my Web Service logs, I can see that a POST request was received but no params were passed and thus it was rejected.
Any help will be greatly appreciated!
PS. I have made sure to Enable CORS on my Rails app.
Pass params inside $save method, pass post_data inside MailingList, so basically this should work
$scope.newMember = function() {
var member = new MailingList();
member.$save({email: $scope.memberData.email});
};

Mongoose $push from HTML Form not working

Can anyone tell me what am I doing wrong.
My HTML Form:
<form action="/user/:id" method="put">
<div class="form-group">
<label>Miles</label>
<input type="text" class="form-control" name="miles">
</div>
<button type="submit" class="btn btn-warning btn-lg">Login</button>
</form>
My Express Route:
app.put('/user/:id', function(req, res) {
User.findById(req.body.params.id, function(err, user) {
if (err)
res.send(err);
console.log(user.id);
User.findByIdAndUpdate(
user.id,
{$push: {"milesLog": {miles: req.body.miles}}},
{safe: true, upsert: true},
function(err, model) {
console.log(err);
},
res.json(user)
);
Posting from my HTML form I get the following Error:
Cannot GET /user?miles=66&activity=asdasd
But When I test this through POSTMAN it works:
What am I doing wrong. Why doesn't it work from my HTML Form?
The route doesn't match, you have this URL
/user?miles=66&activity=asdasd
and then this route
app.put('/user/:id', ....
that route is looking for something like this
/user/66
it doesn't look for querystrings, that would be
app.put('/user', function(req, res) {
var miles = req.query.miles;
var activity = req.query.activity;
and unless you have a really good reason for using PUT request, you should change that to use GET instead.
Also, <form action="/user/:id" ... isn't a valid URL, you can't have colons in the URL, and you seem to have misunderstood a little, the :id in your route matches anything, as long as it's a valid route, so it will match
/user/frank
/user/77
/user/something?querystring
etc. and then you can access that inside the route
app.get('/user/:id', function(req, res) {
var user = req.params.id; // returns "frank" etc
There is no "PUT" verb in html forms, while you are implementing it like this:
<form action="/user/:id" method="put">
You have to use method="POST" in html form and change your route to:
app.post('/user/:id')
It's not a bad thing to use such method.
However if you are developing a front-end application it's common to use XMLHttpRequest object which has "PUT" verb, and your route will work just fine.

Categories

Resources