I am trying to get a user by ID by creating an endpoint on the backend and querying it with the Angular Http service.
What is the correct syntax ?
Here is my current code:
service
voteOn(poll: Poll, userID: string, choice: number) {
var user;
this.http.get('/'+userID)
.map(response => response.json())
.subscribe(json => user = json )
user.votes.push({poll, choice });
const body = JSON.stringify(user);
const headers = new Headers({'Content-Type': 'application/json'});
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
return this.http.patch('https://voting-app-10.herokuapp.com/user'+token, body, {headers: headers})
.map((response: Response) => response.json())
.catch((error: Response) => {
this.errorService.handleError(error);
return Observable.throw(error);
})
.subscribe();
}
route
router.get('/:userid', function (req, res, next) {
var userId = req.params.userid;
UserModel.findById(userID, function (err, user) {
return res.send(user);
});
});
Obviously this is incorrect. The user variable is not defined when user.votes.push is called. How can I assign the result of my first query to user correctly ?
SOLUTION:
voted(poll: Poll, userID: string, choice: number) {
var user;
this.http.get('/'+userID)
.map(response => response.json())
.subscribe(
json => {
user = json;
var result = "";
for (var i = 0; i < user.votes.length; i ++) {
if (user.votes[i].poll == poll.pollId) {
result = "disabled";
if (user.votes[i].choice == choice) {
result = "cheked";
}
}
}
console.log("RESULT:"+result);
return result;
}
)
}