I have recently started learning AngularJS and trying to invoke REST service from AngularJS using $resource.My REST service is up and running and it gives me a json output when I hit the REST url in the browser but when I try to invoke it from AngularJS nothing happens. I am sure I am missing something.I have already googled this issue and also looked at similar questions on stackoverflow but I couldn't get it resolved and hence I am asking it here.
service.js
var services = angular.module('myApp.services', ['ngResource']);
services.factory('AngularIssues',
function($resource){
return $resource('http://localhost:8181/RestCXF5/services/UserInfo/:id', {} ,{
get:{method:'GET' , params: {id: '#id'} }
} );
});
services.value('version', '0.1');
controller.js
myApp.controller('fetchUserDetailsController', ['$scope', 'AngularIssues', function($scope, AngularIssues) {
AngularIssues.get({id:1} , function(UserDetails) {
$scope.UserDetails = UserDetails;
});
}]);
In my index.html , I have added
<script src="lib/angular/angular-resource.js"></script>
This is how I am calling my controller
<div class="col-lg-10" ng-controller="fetchUserDetailsController">
<table ng-table="tableParams" class="table">
<tr>
<td data-title=" 'Name' ">
{{UserDetails.firstName}}
</td>
<td>{{UserDetails.designation}}
</td>
<td>{{UserDetails.employeeId}}</td>
</tr>
</table>
</div>
My problem is that my REST service is not getting called at all and I get blank table in my html. Can anyone please point out what I am missing here?Thanks!!
I even tried using $http service and I get status as 400. Here is the code.
myApp.controller('fetchUserDetailsController' ,
['$scope' , '$http' , function($scope , $http){
$http.get('http://localhost:8181/RestCXF5/services/UserInfo/1').
success(function(data) {
$scope.UserDetails = data;
}).
error(function (data, status, headers, config) {
alert("error" + status);
});
}]);
I think this is wrong;
'http://localhost\\:8181/RestCXF5/services/UserInfo/:id'
You cannot to use the back slash \ instead try
http://localhost:8181/RestCXF5/services/UserInfo/:id
Related
I really dont know what I am doing wrong ...but my app.get function doesn t work ..when I try to look at networking in Chrome ..there was a HTTP status 302 Found ..but its never go into that function on server side ..I really dont know what I am doing wrong ..help please. .or ask more information I dont know what should be the important ..
Here is my server.js function :
app.get('/api/tests/:id', function(req, res, next) {
console.log('get tests id')
console.log(req.params.id)
Test.findById(req.params.id, function(err, test) {
if (err) return next(err);
console.log(test)
res.send(test);
});
});
here is app.js Angular rouiting ..
.when('/tests/:id',{
templateUrl: 'templates/testView.html',
controller: 'TestViewCtrl'
})
.otherwise({
redirectTo: '/'
});
here is my HTML menu.html file ..where I want to go on that specific address:
<div ng-repeat="test in tests">
<div>
{{test.testName}}
</div>
</div>
..in controller menu.html I´ve got post method because GET method too doesnt work ..
$scope.getTests = function () {
$http.post('/api/getTestText')
.success(function (data) {
$scope.tests = data;
and in detail page for each test is my HTML till now blank ..but in Controller I have something like this :
.controller('TestViewCtrl', ['$scope', '$http','$routeParams','Test', function ($scope, $http, $routeParams, Test) {
Test.get({_id: $routeParams.id},function(test){
$scope.test=test;
console.log($scope.test)
and test factory.js :
.factory('Test', ['$resource', function ($resource) {
return $resource('/api/tests/:id');
}]);
I dont think so that the problem is in front-End side ..but maybe is ..
I heard something about postman app from google chrome apps ...but when I type there my HTTP call ..
localhost:3000/api/tests/ and as params I set _id and IDvalue as value ..the result is same like when I do it by click on menu Item ..
localhost:3000/api/tests?id=5726aa164a26bbe4180700ea
But console.log no working in the server.js side ..so it never goes into app.get() I think...
You need to map the _id field from the body into :id in the url param.
To achieve this, change this:
.factory('Test', ['$resource', function ($resource) {
return $resource('/api/tests/:id');
}]);
Into:
.factory('Test', ['$resource', function ($resource) {
//This plugs in the _id field from the body and injects it into the url param.
//This is an example with mongodb default _id field assuming that's what you use.
return $resource('/api/tests/:id', {id: '#_id'});
}]);
I'm writing an Ionic app to read some data from a web API I created with asp.net MVC4. The Ionic app reads the data just fine when I'm hosting it on my local machine but the angular factory does not return anything when I try to read from the web API when it is published on Azure. Is there any logical reason why this wouldn't work when it is published to Azure?
The json string is the same on both when i visit the local and azure site.
[{"ID":1,"Name":"Fireworks","Time":"2015-11-30T21:00:00","Comments":"Be there by 8:00"},
{"ID":2,"Name":"Haircut","Time":"2015-11-30T21:00:00","Comments":"Be there by 8:00"}]
Here is the code for my angular factory
.factory('EventsFactory', ['$http', function($http) {
return $http.get('webAPI link here')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}])
Here is the code for my angular controller
.controller('EventCtrl', ['$scope', 'EventsFactory', function($scope, EventsFactory) {
EventsFactory.success(function(data){
$scope.activities = data;
});
}])
Here is the code for my view
<div class="list card" ng-controller="EventCtrl">
<div class="item item-divider">Upcoming Events</div>
<div class="item item-body" ng-repeat="activity in activities">
<div>{{activity.Name}}</div>
</div>
</div>
Why you add success method with Controller and factory. add success method only controller. like
.factory('EventsFactory', ['$http', function($http) {
return $http.get('webAPI link here');
}])
In your controller, you need to use then
EventsFactory().then(function(data){
$scope.activites = data;
})
I am a newbie to AngularJS. I am using a rails application to expose data in json format. The data is to be used by angular app. The angular repo and the rails repo are completely different. The reason for different repositories is because I want my rails repo just to expose data using APIs which i can use in the angular app.
My rails controller is as below
class Api::V1::PhonesController < ApplicationController
def index
render json: Phone.all
end
def show
render json: Phone.find(params[:id])
end
...
end
Now, when i visit 'localhost:3000/api/v1/phones', it returns me the json data for all the phones. When I visit 'localhost:3000/api/v1/phones/1', it returns the the json data for the phone with id 1. I validated the json data format using http://jsonlint.com/. Everything works fine till here.
My angularjs route file is as:
$routeProvider.
when('/phones', {
templateUrl: 'list.html',
controller: 'PhoneListController'
}).
when('/phones/:id', {
templateUrl: 'show.html',
controller: 'PhoneShowController'
}).
otherwise({
redirectTo: '/phones'
});
}]);
My index.html in the angular repo has the list.html template embedded in it.
<html ng-app='phoneCatApp'>
...
</html>
<script type="text/ng-template" id="list.html">
This is the list template.
</script>
the code for the services.js is as:
var appServices = angular.module('appServices', []);
phoneCatApp.factory('appServices', ['$http', '$q', function($http, $q){
var url = "http://localhost:3000/api/v1/";
//get all phones
this.getPhones = function(){
var defered = $q.defer();
var listApi = url + "phones";
$http.jsonp(listApi).then(function(results){
defered.resolve(results);
}, function(error){
defered.reject(error);
});
return defered.promise;
}
return this;
}]);
The text in the script template is displayed as well when I visit '#/phones'. The problem is that
1) In chrome, following error is displayed when i inspect the page.
Refused to execute script from 'http://localhost:3000/api/v1/phones' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.
2) in firefox, the following error is getting displayed.
SyntaxError: missing ; before statement
Thanks for the help.
Hey so I believe your problem is that your rails controller is returning JSON and NOT JSONP. Your controller has to explicitly specify a callback function, which can be specified by the request params.
See Handling jsonp in rails 3 controller for an example of returning JSONP from a rails controller
So your rails code would look like (argh my rails is very very rusty...):
class Api::V1::PhonesController < ApplicationController
def index
if params[:callback]
format.js { render :json => {:phones => Phone.all.to_json}, :callback => params[:callback] }
else
format.json { render json: {:phones => Phone.all.to_json}}
end
end
Then for the angular side, this answer should help you out:
parsing JSONP $http.jsonp() response in angular.js
And I think your angular would then look like:
var appServices = angular.module('appServices', []);
phoneCatApp.factory('appServices', ['$http', '$q', function($http, $q){
var url = "http://localhost:3000/api/v1/";
//get all phones
this.getPhones = function(){
var defered = $q.defer();
var listApi = url + "phones?callback=JSON_CALLBACK";
$http.jsonp(listApi).then(function(results){
defered.resolve(results);
}, function(error){
defered.reject(error);
});
return defered.promise;
}
return this;
}]);
I have a basic app, that fetches some data through the $http service, however it doesnt render the data correct in the template, when the template is served from the template cache. My code looks like this:
angular.module('app', [])
api service:
.factory('api', function($http, $q) {
return {
getCars: function() {
return $http.get('api/cars');
}
};
})
the controller using the service:
.controller('carsCtrl', function($scope, api) {
api.getCars().success(function(data) {
$scope.cars = data;
});
})
the route setup:
.config(function($routeProvider) {
$routeProvider.when('/cars', {
templateUrl: 'cars.html',
controller: 'carsCtrl'
});
});
and the template cars.html
<div ng-repeat="car in cars">
{{ car }}
</div>
this works the first time the browser hits /cars, however, if I push the back on forward button in the browser to hit the url a second time without a page reload, the {{car}} is not being rendered. If the cars.html is put in the templateCache like this:
angular.module('app').run(function($templateCache) {
$templateCache.put('cars.html', '<div ng-repeat="car in cars">{{ car }}</div>');
});
the {{car}} binding is not rendered either.
I suspect this has something to do with Angular not unwrapping promises in templates anymore, but not totally sure. Does anyone know what I am doing wrong and how to write this code correctly?
Well, I saw some syntax errors in your code (maybe you didn't copy the code but typed it manually for SO not sure). Also you returned deferred instead of deferred.promise. What you trying to achieve works just fine:
Plnkr Example
Im trying to get my Google Plus Page's posts, activity feed via JSON to display on my website.
Im using AngularJS to do that. Im not sure what im doing wrong.
When I run this, in the page it doesnt show anything.
Also, I get CONSOLE error: Uncaught SyntaxError: Unexpected token : public:2
'use strict';
var app = angular.module('teamamr', ['teamamr.controller']);
var controllers = angular.module('teamamr.controller', []);
controllers.controller('googlePosts', function ($scope, $http) {
$http.jsonp('https://www.googleapis.com/plus/v1/people/117069052843337874560/activities/public?maxResults=10&key=MYKEY')
.then(function (data) {
$scope.items = data;
console.log(data);
});
});
HTML PART: while html tag has ng-app="teamamr"
<div class="w-row" ng-controller="googlePosts">
<div class="w-col w-col-4 services" ng-repeat="post in items">
<h3>{{post.title}}</h3>
<p>read more</p>
</div>
</div>
Could you try to replace your JSONP call by this one
$http.jsonp('https://www.googleapis.com/plus/v1/people/117069052843337874560/activities/public?callback=JSON_CALLBACK&maxResults=10&key=MYKEY').success(function(data, status, headers, config) {
console.log(data);
$scope.items = data.items;
});
Please note that I have added a &callback=JSON_CALLBACK in the url and replace then(...) by success(...)