ASP MVC Angular JS $http not found - angularjs

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

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.

Angular JS $http Post with REST query parametres

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.

AngularJS factory. I need to call a method in a factory passing in a parameter then I need to retrieve the result from a different controller

I am new to AngularJS. I am building an email front-end as a college project.
I have an inbox view that retrieves emails from a json file. It works as expected by making this call: $scope.emails = InboxService.query();.
When the user clicks on an email they are redirected to a new page where I want to view the email, also from a json file (for testing only).
The controller:
app.controller('InboxController', function ($scope, $location, InboxService, EmailService) {
//Make call to email by id
$scope.viewEmail = function(emailId)
{
//DOES NOT WORK
EmailService.find({id: emailId});
$location.path('inbox/email/' + emailId);
};
//Make call to inbox
$scope.emails = InboxService.query();
});
When the user clicks on an email I want to use the id to retrieve another json file and pass it to a separate controller for a new page.
This is my EmailController:
app.controller('EmailController', function ($scope, InboxService, EmailService) {
$scope.emails = {};
//DOES NOT WORK
EmailService.getEmail(function(response){
$scope.emails.email = response;
});
});
This is the email service: DOES NOT WORK
app.factory('EmailService', function ($resource) {
var thisEmail = {};
thisEmail.find = function () {
thisEmail = $resource('json/message/:id.json', {}, {
get: {method: 'GET', params: {id: '#id'}}
})
},
thisEmail.getEmail = function () {
return thisEmail;
};
return thisEmail;
});
The service does not do what i want. I want to retrieve a json file using an id, then be able to access that file in the EmailController.
Try:
app.factory('EmailService', ['$resource',function ($resource) {
return $resource('json/message/:id.json', {}, {
get: {method: 'GET', params: {id: '#id'}}
});
}]);
In your controller:
EmailService.get({id:emailId});
You should use the built in state provider https://docs.angularjs.org/api/ngRoute/service/$route
or https://github.com/angular-ui/ui-router/wiki instead of directly working with the location hash.

How can I change the base URL of an AngularJS HTTP call?

My application calls $HTTP many times like this:
this.$http({
method: this.method,
url: this.url
})
The this.url is always set to something like /app/getdata
Now I have moved the back-end of my application to another server and I will need to get data like this:
https://newserver.com/app/getdata
Is there a way that I can supply a base URL that will be used for all the $http calls?
I found a alternative solution instead of <base> tag:
written in coffeescript
$httpProvider.interceptors.push ($q)->
'request': (config)->
if config.url.indexOf('/api') is 0
config.url = BASE_URL+config.url
config
I usually keep settings in angular constants and inject them to services.
I tend to keep my urls close to where they are needed. So if I have a service, then I'd keep the base url there; like this: this.rootUrl = '/api/v1/';
This allows me to have additional contextual methods that 'extend' the url.
For example:
this.getBaseUrl = function(client_id, project_id) {
return this.rootUrl + 'clients/' + client_id + '/projects/' + project_id + '/';
};
Which I can then use like this:
this.createActivity = function(client_id, project_id, activity_name, callback) {
$http.post(this.getBaseUrl(client_id, project_id) + 'activities', {activity: {name: activity_name}})
.success(callback)
.error(this.handlerError);
};
or like this (within the same service):
this.closeActivity = function(activity_id, callback){
$http.get(this.rootUrl + 'close_activity/' + activity_id)
.success(callback)
.error(this.handlerError);
};
set baseUrl in $rootScope:
app.run(function($rootScope) {
$rootScope.baseUrl = "https://newserver.com";
});
add $rootScope into your app's controllers:
app.controller('Controller', ['$rootScope', function($rootScope){
...
this.$http({
method: this.method,
url: $rootScope.baseUrl + this.url
})

AngularJS ngResource not sending custom header

I'm attempting to use ngResource to query a REST API. I need to specify my API key in a custom header. I've tried it like so:
angular.module('ApiService', ['ngResource'])
.factory('Api', ['$resource', function($resource) {
this.apiEndpoint = '';
this.apiKey = '';
return {
init: function(apiEndpoint, apiKey) {
this.apiEndpoint = apiEndpoint;
this.apiKey = apiKey;
},
get: function(collection) {
return $resource(this.apiEndpoint + 'api/1/' + collection, {},
{
get: {
method: 'JSONP',
headers: {'api_key': this.apiKey},
params: {callback: 'JSON_CALLBACK'}
}
}
).get();
}
};
}]);
which I then use in my controller like:
app.controller('MyCtrl', function ($scope, Api, ENV) {
Api.init(ENV.apiEndpoint, ENV.apiKey);
var widgets = Api.get('widgets');
});
My custom header isn't set when I inspect the XHR. Also, why will the XHR not run until I call an empty .get() after the initial $resource:get() method?
I've also tried to set the headers in $httpResource directly:
.config(function($httpProvider) {
$httpProvider.defaults.headers.get = {'api_key': 'abc123'};
})
but this still doesn't set the custom header when I inspect the network request. What am I missing?
This issue is, of course, that I was using JSONP in this request, which doesn't include the ability to craft headers when making a request. See how to change the headers for angularjs $http.jsonp.
Specifically, JSONP simply includes a <script> tag at the bottom of the DOM to load cross-domain javascript, so it's up to your browser to send the default headers.

Resources