Calling $http.delete but nothing happens - angularjs

I'm actually working on a webclient calling a REST service.
After my last question, the GET request is working now.
Now i want o implement a DEL request using angulars delete method.
In the following example is my service request implemented.
function ItemsService($http) {
this.$http = $http;
}
ItemsService.prototype = {
deleteFoo: function (id) {
this.$http.delete('http://localhost:3001/posts/' + id)
.then(function successCallback(response) {
console.log("DEL send...");
console.log(response.data);
}, function errorCallback(response) {
console.log('Error');
});
}
}
module.exports = {
ItemsService: ItemsService
}
I added a button on the webpage with ng-click="$ctrl.deleteMe()".
The controller looks like the following example:
function Foo(ItemsService) {
this.itemsService = ItemsService;
}
Foo.prototype = {
deleteMe: function () {
console.log('delete now');
this.itemsService.deleteFoo(1).then(
response => {
console.log('gelöscht? ' + response);
}
);
}
};
If i now click on the button, nothing happens. In the network trace log in the dev tools in the browser i can't see a DEL request.
To test this REST service request, i run the JSON Server tool on port 3001.
I testet the availability of the server with SOAPUI, it works, i see all the requests in the console.
But no request from my test webpage.
Can anyone help me?

You need to return
return this.$http.delete('http://localhost:3001/posts/' + id)
.then(function successCallback(response) {
console.log("DEL send...");
console.log(response.data);
}, function errorCallback(response) {
console.log('Error');
});

Related

angularjs menu disappear after http call

I am using AngularJS, and when I use http call, the menu disappears if the request returns 404 not found.
When the http call is ok, every thing works fine.
this is my code
this.fetchList = function () {
var url = '/api/getlistmanager';
return $http.get(url).then(function (response) {
return response.data;
}).catch(function (response) {
if(response.status==404)
response.status=500;
return response.status;
}).finally(function () {
;
});
};
Any idea please for catching this type of call without blocking the menu?
thanks for help

Best way to compare two API calls in angularJS?

I have an AngularJS frontend to my API-based application. There are services which make API calls, such as the following. I want to compare a variable from each of these calls:
Get the user data:
this.getUserData = function () {
var apiCall = $http({
method: 'GET',
url: 'http://example.com/api/userdata',
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('token'),
'Access-Control-Allow-Origin': 'Any'
}
});
return apiCall;
};
Get the page data:
this.getPageData = function(slug){
var apiCall = $http.get('http://example.com/api/public/page?slug=' + slug, {
headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') }
}
)
return apiCall;
};
In my controller I wish to compare a var from each of these calls, like so :
if (apiService.getUserData.likes.page_id == apiService.getPageData.page_id){ // do stuff }
What is the most efficient way of doing this, given that API calls can take a while.. I don't have to make an API call everytime I want to access a variable from the API do I? Bear in mind that these API calls would normally be made in DIFFERENT controllers, so the results are stored in different scopes.
Basically, I'm confused whether that bit of logic should go in a controller, in the service itself, or somewhere else. Any advice is appreciated. Thanks.
If you are comparing them in a controller you can easily call one followed by the other and compare. Since you say you have an "API-based application" and use an auth token from localStorage you should call the API in each different controller you have in case your auth token expires or something.
I would most likely create a service like (flushing it out to more to show all pieces):
angular.module('app').service('CompareService', CompareService);
CompareService.$inject = ['apiService', '$q'];
function CompareService(apiService, $q) {
return {
arePageIdsEqual: apie
};
function apie() {
var deferred = $q.defer();
apiService.getUserData().$promise.then(function(userData) {
apiService.getPageData().$promise.then(function(pageData) {
deferred.resolve(userData.likes.page_id === pageData.page_id);
}, function(err) {
deferred.reject(err);
});
}, function(err) {
deferred.reject(err);
});
return deferred.promise;
}
}
And in your controller just inject it and call it like:
CompareService.arePageIdsEqual(function(yes) {
if(yes) {
// do something
}
}, function(err) {
// err making the calls
});
You should implement it with a Promise.all.
function doCompare(userData,pageData){
if (userData.likes.page_id == pageData.page_id){
// do stuff
}
}
var promises = [apiService.getUserData,apiService.getPageData]
$q.all(promises).then(doCompare);

console service response inside controller

i have written a service with take parameter on the basis of which it response me with the response of http request.
this.getPaymentDueDetails=function(date){
this.getfromRemote('paymentdue/'+btoa(date))
.success(function(response){
return response;
})
.error(function(response){
return false;
})
}
getfromRemote is my another service which make http request
now i am trying to get the response of this service call inside my controller function
$scope.callDueReports=function(blockNum){
var data;
data=myAngService.getPaymentDueDetails('2015-04-20');
console.log(data);
}
its quite obvious that i wont get any thing in data as the page loads initially but i want the result of getPaymentDueDetails int it.
Please modify your service to return the promise like below.
this.getPaymentDueDetails = function(date) {
return this.getfromRemote('paymentdue/' + btoa(date));
};
And in controller check if the promise is resolved.
$scope.callDueReports = function(blockNum) {
var data;
myAngService.getPaymentDueDetails('2015-04-20').then(function(dataFromService) {
data = dataFromService;
console.log(data);
})
.catch(function(response) {
console.error('error');
});
};

ng mock e2e Unexpected Request

I'm using the ngMockE2E to mock the httpBackend while developing the UI in Angular JS. The App runs on a Grizzly-Server with a backend which is provided by a virtual machine. Now when I go on the Website the Console logs the Error:
Unexpected request: GET /api/info
No more request expected
In my case I only want to mock the data of one database. Additional to that I want to turn the mock ON/OFF on the fly via a button. This was working until the Error comes up.
For that case I've written the following:
$httpBackend.whenPOST(function (url) {
if (!mockup) {
return false;
}
var target_url = (someUrl);
return target_url === url;
}).respond(function (method, url, data) {
return [200, [someData], {}, 'mockupData'];
}
);
Additional to that I've added the following to pass all the other requests:
// pass the rest of the queries
$httpBackend.whenGET(/.*/).passThrough();
$httpBackend.whenPOST(/.*/).passThrough();
$httpBackend.whenPUT(/.*/).passThrough();
$httpBackend.whenDELETE(/.*/).passThrough();
So for all of you who face the same problem. I found a workaround for the issue. But I'm sure there should be another better solution.
For that I used an Interceptor which is also provided by angular. Here the api
So I wrote this:
app.factory('httpInterceptor', function () {
return {
'response': function (response) {
// therefore you can enable the mockup with a switch or a button
if (!mockup) {
return response;
}
try {
// in the config object is the requested url
if (response.config.url !== someUrl) {
// don't intercept; return response unchanged
return response;
}
// found an url which should be mocked
// generate or modify the data
var generatedData = generateSomeData();
response.data.push(generatedData)
return response;
} catch (TypeError) {
// don't intercept
return response;
}
}
}
}
);
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
}]);

AngularJS reload data after PUT request

Should be a fairly easy one here for anyone who knows Angular. I am trying to update the data that is displayed after I make a PUT request to update the object. Here is some code:
Post service (services/post.js)
'use strict';
angular.module('hackaboxApp')
.factory('Post', function($resource) {
return $resource('/api/posts/:id', {id : '#id'}, {
'update': { method: 'PUT' }
})
});
Server side controller function that gets executed when trying to update data (lib/controllers/api.js)
exports.editsave = function(req, res, next) {
var posty = req.body;
console.log(posty._id.toString() + " this is posty");
function callback (err, numAffected) {
console.log(err + " " + numAffected);
if(!err) {
res.send(200);
//res.redirect('/forum');
}
}
Post.update(posty, { id: posty._id.toString() }, callback);
};
This is the console output for the above code:
53c54a0d4960ddc11495d7d7 this is posty
null 0
So as you can see, it isn't affecting any of the MongoDB documents, but it also isn't producing errors.
This is what happens on the client (Angular) side when a post is updated:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
// Now call update passing in the ID first then the object you are updating
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
After the redirect, $location.path('/forum'), none of the data is displayed as being updated...when I look in the database...nothing has changed either...it is like I am missing the step to save the changes...but I thought that update (a PUT request) would do that for me.
I use ng-init="loadposts()" when the /forum route is loaded:
$scope.loadposts = function() {
$http.get('/api/posts').success(function (data) {$scope.posts = data});
};
Shouldn't all the new data be loaded after this? Any help would be appreciated. Thanks!
Your server side output indicate that the update query doesn't match any document in the database.
I'm guessing that you are using Mongoose in NodeJS server side code to connect to mongodb.
If that the case, your update statement seems incorrect.
Instead of { id: .. } it should be { _id: .. }
Also the conditions object and updated object are swapped.
The statement should be like this:
Post.update({ _id: posty._id.toString() }, posty, callback);
If you are not using Mongoose, please eloborate more on which library you are using or better than that, show the code where the Post variable is defined in your server side code.
Ok I got it.
the problem is that you are not using the Angular resource api correct.
This code need to be changed:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
Into:
// Update existing Post
$scope.saveedit = function() {
var editedpost = new Post($scope.post); //New post object
editedpost.$update(function() {
$location.path('/forum');
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
And as for the server code (taken from my own working module):
exports.update = function (req, res) {
var post == req.post;
post = _.extend(post, req.body);
post.save(function (err) {
if (err) {
return res.send(400, {
message: getErrorMessage(err)
});
} else {
res.jsonp(post);
}
});
};

Resources