Angular JS $http Post with REST query parametres - angularjs

I am pretty new to Angular JS technology.
I want to call following protected REST URL.
http://localhost/rest/bpm/wle/v1/search/query?condition=taskActivityName|Equals|Cashier Review&condition=taskStatus|Equals|Received&organization=byTask&run=true&shared=false&filterByCurrentUser=false
Following code is not working for me. It is taking only `http://localhost/rest/bpm/wle/v1/search/query .Please suggest.
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
var URLBASE = "http://localhost/rest/bpm/wle/v1";
var userid = "harish.puli";
var password = "Password1";
// End of buildAuthorization
var options =$.param ({
query : {
organization : "byTask",
condition : [ "taskActivityName|Equals|Cashier Review", "taskStatus|Equals|Received" ]
},
handleAs : "json",
user: "harish.puli",
password: "Password1"
});
var url=URLBASE+"/search/query";
$http.post(url,options).success(function (response) {
console.log(response);
$scope.tasks = response.data.data;
});
});

I believe you're missing a '?' after query based on the URL you provided.
Try:
var url=URLBASE+"/search/query?";

Your code is only calling http://localhost/rest/bpm/wle/v1/search/query because you're using post instead of get. In get you transmit the parameters in the URL but in post they are transmitted in the body of the request.

Related

How to get the data of multiple cities using openweathermap api in angularjs?

I am new in angularjs, i want to get that data of multiple cities in angularjs.
Here is code.:
var app = angular.module('jsbin', []);
app.controller('DemoCtrl', function($http) {
var vm = this;
var vm1 = this;
var URL = 'http://api.openweathermap.org/data/2.5/forecast/daily';
var request = {
method: 'GET',
url: URL,
params: {
q:'',
mode: 'json',
units: 'imperial',
cnt: '7',
appid: '4e1869d8da618fde99e84483*******'
}
};
$http(request)
.then(function(response) {
vm.data = response.data.list ;
console.log(response.data);
}).
catch(function(response) {
vm.data = response.data;
});
});
I think this is what you're looking for:
var URL = http://api.openweathermap.org/data/2.5/group?id=524901,703448,2643743&units=metric
Source: http://openweathermap.org/current#severalid
EDIT:
If the endpoint doesn't cut it for you, you might have to use $q.all to execute multiple 'http://api.openweathermap.org/data/2.5/forecast/daily' in parallel
I see that OpenWeatherMap deleted for some reason this endpoint from docs, but not from the API itself.
Right now the working API call for several cities by id looks like this.
var URL = http://api.openweathermap.org/data/2.5/group?id=524901,703448,2643743&units;=metric&appid={API_KEY}
Found the docs regarding this request only in web archive in January 2021.

ngResource - doesn't show data in browser

i have problem with ngResource.
here is my .factory
app.factory('sveKlupeServiceFactory', ['$resource',
function($resource){
return $resource('myURL/to/json', {},{
// { method: 'getKlupe', q: '*' },
query: { method: 'GET', params:{klupaId:'klupe'}, isArray:true}
});
and here is my controller
app.controller('klupeController', ['$scope', 'sveKlupeServiceFactory', function ($scope,sveKlupeServiceFactory){
$scope.klupe = sveKlupeServiceFactory.query();
}]);
and in html I have this
<tr ng-repeat="klupa in klupe">
<td>{{klupa.serial_number}}</td>
<td>{{klupa.location_id}}</td>
<td>{{klupa.type}}</td>
<td>{{klupa.last_report_dt}}</td></tr>
Problem:
in my browser I have table, but with empty row. There is no any error.
In my app I have
var app = angular.module('App', [
'ngRoute',
'ngResource']);
Can someone help me with any suggestion?
Thank you.
If you want entire table data, then there is no need to pass id as parameters in factory.Make the following changes in controller while calling factory method.
Check the response using console.log()
sveKlupeServiceFactory.query(function(res){
console.log(res);
$scope.klupe = res;
});
You should use promises to get the response.
$scope.klupe = sveKlupeServiceFactory.query();
$scope.klupe.$promise.then( function(result) { $scope.klupe = result });

ASP MVC Angular JS $http not found

I have a problem with calling http get to WebApi controller from my angular code. I am using ASP MVC just to provide start page and the start page url looks like: http://localhost:23845/StudentsEditor/StudentsView and now from angular I am callinh http request:
angular.element(document).ready(function () {
$http({
method: "GET",
url: "api/Groups/GetGroups",
dataType: "json",
}).then(function successCallback(response) {
$scope.groups = response.data;
}, function errorCallback(response) {
alert("trouble...");
});
and I am getting 404 because the URL is incorrect. It concats the path and it loks like:
GET http://localhost:23845/StudentsEditor/api/Groups/GetGroups
instead of http://localhost:23845/api/Groups/GetGroups
plese give me some advice hoe to resolve it. Of course I have defined RouteConfig:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "StudentsEditor", action = "StudentsView", id = UrlParameter.Optional }
);
and the webApi config:
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{url}/api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
You should not hard code url's like that. You may use the Url.Content or Url.RouteUrl helper methods in your razor view to generate the relative url to the app base/root. It will take care of correctly building the url regardless of your current page/path. Once you get this value, You can use angular's value provider to pass this data from your razor view to your angular controller/ angular data services.
So in your razor view (Specific page/ Layout file), You may add this.
<script>
var myApp = myApp || {};
myApp.Urls = myApp.Urls || {};
myApp.Urls.baseUrl = '#Url.Content("~")';
</script>
<script src="~/Scripts/AngularControllerForPage.js"></script>
<script>
var a = angular.module("app").value("appSettings", myApp);
</script>
and in your angular controller, the appSettings will be injected and you can use that and build the correct url to your other web api end points.
var app = angular.module("app", []);
var ctrl = function (appSettings,$http) {
var vm = this;
vm.baseUrl = appSettings.Urls.baseUrl;
//build other urls using the base url now
var getUGroupsUrl = vm.baseUrl + "api/Groups/GetGroups";
// you can use getUGroupsUrl now for your http calls.
console.log(getUGroupsUrl);
$http.get(getUGroupsUrl).then(function(response) {
console.log(response.data);
}
};
ctrl.inject=['$http'];
app.controller("ctrl", ctrl)
You may also consider moving your web api calls from your angular controller to a data service to keep things clean & keep concern separated.
I found easy way to accomplish what I was looking for:
angular.element(document).ready(function () {
$http({
method: "GET",
url: window.location.origin + '/api/Groups/GetGroups',
dataType: "json",
}).then(function successCallback(response) {
$scope.groups = response.data;
}, function errorCallback(response) {
alert("trouble..");
});
});
and the key is window.location.origin which returns protocol + host + port

How to send the `form data` with id's in angular resource save method?

I need to save the data using angular save method ( 'post'). how can i send the necessary id is with form data?
at present i am getting an error as 'Invalid HTTP status code 405`.
here is my controller.js:
$scope.uploadFile = function ( newFile, id ) {
var data = new FormData();
server.uploadXML.save({
//passing id's
packageId: $scope.packageId,
contractorId : $scope.contractorId,
contractId : id
}, { save: {
//passing data..is it correct?
data: newFile[0]
}});
}
here is my server.js:
(function () {
"use strict";
angular
.module("tcpApp")
.factory("server", ['$resource', function ($resource) {
var base = 'http://azvsptcsdev02:678/_vti_bin/CPMD.WEBSERVICE/ProjectInfoService.svc/';
return {
uploadXML : $resource( base + 'UploadContract/:packageId/:contractorId/:contractId')
}
}]);
})();
You need to specify which type of request it is.. GET/POST/PUT etc
405 comes when the method is not allowed, which means either the request type is wrong or the endpoint is not defined.
Hope this helps.

Accessing liked images of instagram API with Angular

I'm trying to access the JSON of the liked media of a particular instagram user, in the documentation it says to use this:
https://api.instagram.com/v1/users/self/media/liked?access_token=ACCESS-TOKEN
as mentioned here:
https://instagram.com/developer/endpoints/users/
replacing ACCESS-TOKEN with the one given by instagram which I've done below:
(function(){
var app = angular.module('instafeed', []);
app.factory("InstagramAPI", ['$http', function($http) {
return {
fetchPhotos: function(callback){
var endpoint = "https://api.instagram.com/v1/users/self/media/liked/?";
endpoint += "?access_token=[ACCESS-TOKEN]";
endpoint += "&callback=JSON_CALLBACK";
$http.jsonp(endpoint).success(function(response){
callback(response);
});
}
}
}]);
app.controller('ShowImages', function($scope, InstagramAPI){
$scope.layout = 'grid';
$scope.data = {};
$scope.pics = [];
InstagramAPI.fetchPhotos(function(data){
$scope.pics = data;
console.log(data)
});
});
})();
obviously I have replaced ACCESS-TOKEN with mine, but nothing is given back, is there something incorrect?
EDIT: I added the callback but still it comes back as undefined.
To make this work using jsonp, add the following to your endpoint url:
&callback=JSON_CALLBACK
Your callback needs to be named 'JSON_CALLBACK'. Find out why here: https://docs.angularjs.org/api/ng/service/$http#jsonp
Otherwise, to make a simple GET request...
$http.get(endpoint).success(function(data){
callback(data);
});
It's jsonp, so my guess is that you should specify name of the callback function in your URL:
var endpoint = "https://api.instagram.com/v1/users/self/media/liked/?callback=callback";

Resources