Reputation: 25
My GET request works but my PUT request doesn't seem to trigger. The function it is inside of definitely runs because the console.log statements show in my console. The console.log statements inside the http PUT request don't show in the google chrome console or in my terminal.
Angular:
getCitiesSaved(): Observable<string[]> {
return this.http.get(this.url).map((data: Response) => {
this.currentCityList = data.json().cityAlerts;
return data.json().cityAlerts;
});
}
addCity(cityName) {
let cityArr = this.currentCityList;
cityArr.push(cityName);
const body = JSON.stringify({
id: this.userId,
cityAlerts: cityArr
});
const headers = new Headers({ 'Content-Type': 'application/json' });
console.log(body);
return this.http
.put(this.url, body, { headers: headers })
.map((response: Response) => {
console.log('http put request ran in frontend');
response.json();
})
.catch((error: Response) => {
this.errorService.handleSigninError(error.json());
return Observable.throw(error.json());
});
}
Express:
router.get('/users/:id', (req, res) => {
console.log('get user info');
User.findOne({
_id: req.params.id
}).exec((err, user) => {
if (err) {
return res.status(500).json({
title: 'An error occured',
error: err
});
} else {
console.log(user);
res.status(200).json(user);
}
});
});
router.put('/:users/:id', (req, res) => {
console.log('backend triggered');
User.findOneAndUpdate(
{
_id: req.params.id
},
{ $set: { cityAlerts: req.body.cityAlerts } },
{ upsert: true },
function(err, newCityAlert) {
if (err) {
console.log(err);
} else {
console.log(newCityAlert);
res.send(newCityAlert);
}
}
);
});
Upvotes: 1
Views: 1463
Reputation: 134
You have to call subscribe
on your observable before the request executes.
It looks like you need to change map
to subscribe
within addCity()
.
From the docs: https://angular.io/guide/http
Note the subscribe() method. All Observables returned from HttpClient are cold, which is to say that they are blueprints for making requests. Nothing will happen until you call subscribe(), and every such call will make a separate request. For example, this code sends a POST request with the same data twice:
Their Example:
const req = http.post('/api/items/add', body);
// 0 requests made - .subscribe() not called.
req.subscribe();
// 1 request made.
req.subscribe();
// 2 requests made.
I hope that helps - I stumbled over this too.
Upvotes: 3