After successfully finishing this tutorial, I started building my app routes to handle the creation of some dummy models in the database, which works just fine when I request them through Postman app (using the follwing URL: https://lab4-roger13.c9users.io:8080/api/nerds).
The next step, was to create a service in AngularJS to allow the user to request those same informations at the client side. At the end of the tutorial I was left with this:
angular.module('NerdService', []).factory('Nerd', ['$http', function($http) {
return {
// call to get all nerds
get : function() {
return $http.get('/api/nerds');
},
a : 2,
// these will work when more API routes are defined on the Node side of things
// call to POST and create a new nerd
create : function(nerdData) {
return $http.post('/api/nerds', nerdData);
},
// call to DELETE a nerd
delete : function(id) {
return $http.delete('/api/nerds/' + id);
}
}
}]);
And this is the module that links all my services and routes:
angular.module('sampleApp',
['ngRoute', 'appRoutes', 'MainCtrl', 'NerdCtrl', 'NerdService'])
.controller('nerdDB', ['$scope', 'Nerd', function($scope, Nerd) {
$scope.a = Nerd.a;
}]);
Here is a sample of a backend route I'm trying to access:
module.exports = function(app) {
// get all nerds in the database (accessed at GET https://lab4-roger13.c9users.io:8080/api/nerds)
app.get('/api/nerds', function(req, res) {
// use mongoose to get all nerds in the database
Nerd.find(function(err, nerds) {
// if there is an error retrieving, send the error.
// nothing after res.send(err) will execute
if (err)
res.send(err);
res.json(nerds); // return all nerds in JSON format
});
});
As you can imagine, I can access the a property of the service at the html by using the {{a}} notation, which displays 2. But when I try the same with the get property, nothing shows up.
I'm not sure, is the URL the tutorial provides at the $http.get wrong or am I missing a step to do and access the GET response?
(If I missed any relevant code, they are the same as the ones that can be found at the tutorial link)
Nerd.get() is a function that returns a promise from the $http service. If you want to show it's result in your view, you can bind the results to your view like so:
.controller('nerdDB', ['$scope', 'Nerd', function($scope, Nerd) {
Nerd.get().then(function(nerds) {
$scope.nerds = nerds;
});
}]);
loved this post I had some problem using factory and found solution here
nerds controller
angular.module('NerdCtrl', []).controller('NerdController', function($scope, Nerd) {
$scope.tagline = 'bla bla';
$scope.nerds = {};
Nerd.getNerd()
.then(function (components) {
$scope.nerds = components;
}, function (error) {
console.error(error);
});
});
As service
angular.module('NerdService', []).factory('Nerd', function ($q, $http) {
return {
getNerd: function () {
var deferred = $q.defer(),
httpPromise = $http.get('/api/nerds');
httpPromise.success(function (components) {
deferred.resolve(components);
})
.error(function (error) {
console.error('Error: ' + error);
});
return deferred.promise;
}
};
});
In NerdHTLM using controller to loop records
<table ng-controller="NerdController" >
<tbody>
<tr ng-repeat="nerd in nerds">
<td>{{nerd.name}}</td>
<td>{{nerd.type}}</td>
</tr>
</tbody>
</table>
Related
So, I am doing VERY SIMPLE controller like I've done before on my personal website I made back 8 years ago.
What I'm facing is an enormous app with code that followed no coding standards.
Here's my controller, inside a controller.js file:
app.controller("documentController", ["$scope", "documentService", ($scope, documentService) => {
let docCtrl = $scope;
//docCtrl = 'Hello World!';
docCtrl.docContent = [];
console.log('DOC CONTROL: ', docCtrl.content);
docCtrl.fetchDocs = function () {
documentService.getDocuments().then(function (result) {
docCtrl.docContent = result.data;
console.log('DOCS RETRIEVED: ', docCtrl.docContent);
});
}
docCtrl.fetchDocs();
}]);
and the service I need call inside a service.js file that's in the same module folder.
app.service('documentService', ["$http", "URL", ($http, URL) => {
let getDocuments = function () {
return $http.get(URL)
.success(function (data) {
console.log('SUCCESS: Documents retreived', data);
return data;
})
.error(function (e) {
console.log(`He's dead Jim!`, e);
return e;
})
}
return ({
getDocunment: getDocuments
});
}]);
Inside that controller.js file is a 2584 line controller set up the same way as my very simple controller that calls an 1000 line service in the service.js file.
My code sits at the bottom.
What happens is, when I run the app, I get UNK Provider error for the service.
Oh, I have a directive that also sits in the controller.js which is found and works.
app.directive("documentDirective", ["$compile", ($compile) => {
let data = {};
data.restrict = 'AE';
data.link = async ($scope, $element) => {
const template = '<span>Hello World!</span>'
await $element.html('').append($compile(template)($scope));
};
return data;
}]);
So, when I take out the call to the service, which I need, I get no errors.
When I put the service in the app.controller() that already exists in the controller.js file and call it, I still get UNK Provider. This makes ABSOLUTELY no sense.
[$injector:unpr] http://errors.angularjs.org/1.5.7/$injector/unpr?p0=URLProvider%20%3C-%20URL%20%3C-%20documentService
My personal website: www.peterborreggine.us, if you open the debug console and view: the Angular folder --> Controllers and Services, you'll see how I'm doing exactly what I am trying to accomplish here.
Of note, there are 65 module folders in the module directory all with their own controller.js and service.js. But only one controller and one service per file is there.
Again, I've been using Angular since its inception and now on Angular 12. This telecom company needs to upgrade to at least Angular 12
UPDATE:
I just tried this with the same UNK Provider error and this is suggested in Angular's error above! I combined both the service and controller and STILL the same error
// Combined Service and then my Controller
app.service('documentService', ["$http", "URL", ($http, URL) => {
let getDocuments = function () {
return $http.get(URL)
.success(function (data) {
console.log('SUCCESS: Documents retreived', data);
return data;
})
.error(function (e) {
console.log(`He's dead Jim!`, e);
return e;
})
}
return ({
getDocunment: getDocuments
});
}]).controller("documentController", ["$scope", "documentService", ($scope, documentService) => {
let docCtrl = $scope;
//docCtrl = 'Hello World!';
docCtrl.docContent = [];
console.log('DOC CONTROL: ', docCtrl.content);
docCtrl.fetchDocs = function () {
documentService.getDocuments().then(function (result) {
docCtrl.docContent = result.data;
console.log('DOCS RETRIEVED: ', docCtrl.docContent);
});
}
docCtrl.fetchDocs();
}]);
this is my angular controller which i use it in laravel but when i submit my form i get
MethodNotAllowedHttpException
app.service('post_service', function ($http) {
create = $http.POST('/post', JSON.stringify(data)).then(
function mySuccess(response) {
debugger
$scope.myWelcome = response.data;
},
function myError(response) {
debugger
$scope.myWelcome = response.statusText;
}
)
});
app.controller('postController', ['$scope', function ($scope, post_service) {
$scope.message = 'AddPosts';
// $scope.post=null;
$scope.save = function (data) {
post_service.create(data)
}
}]);
my route config is this :
Route::resource('post', 'PostController');
like you see i using resource controller which allow us to use all type of routing like store index or....
for more detail: my form is simple angular form which contains no token string like csrfToken or some thing like that
You can use the this Route::post('/postData', 'PostController#action');
in the angular service
$http.POST('/postData', JSON.stringify(data)).then(
code here
);
I have the following controllers which all the ngResource services to get data.
.controller('venueCtrl', function ($scope, $stateParams, VenueService) {
$scope.venue = VenueService.get({ id: $stateParams.id });
})
.controller('tomorrowCtrl', function ($scope, EventService) {
var evts = EventService.query({ period: "Tomorrow" });
evts.$promise.then(function (response) { $scope.events = response; });
}).....
Now I need to add error handling (for example, display an alert box) for the error situations, e.g., no network, web service failed, etc. How to add the code to handle the errors?
You can use Interceptors this way:
angular.module('ngRessourceErrorsHandler', [])
.config(function($resourceProvider) {
angular.forEach($resourceProvider.defaults.actions, function(action) {
action['interceptor'] = {
responseError: function(httpResponse) {
//Do whatever you want here !
}
};
})
});
Please try this and let me know if this works for you. Don't forget to add ngRessourceErrorsHandler dependency to your module or just use config directly.
I'm using the same HTTP method in different controller like following sample:
Service:
var method="sampleMethod"
HotalStatisticService.GetReservations = function (data) {
return $http({
method: 'POST',
data: data,
cache: false,
url:'http://sample.com/'+method
});
}
first controller
.controller("SampleACtrl", function ($scope,HotalStatisticService ) {
HotalStatisticService.GetReservations({start:start, end:end, type:type})
.success(function (data) {
$scope.sampleA=data;
})
}
second controller
.controller("SampleBCtrl", function ($scope,HotalStatisticService ) {
HotalStatisticService.GetReservations({start:start, end:end, type:type})
.success(function (data) {
$scope.sampleB=data;
})
}
How do I use here method in the only one controller?
Let me say that the other solution that uses factories is probably a MUCH better solution.Using Services is also a good option.
Another ,perhaps crude way to do it is using $rootScope.Answer below.
What you essentially want to do is share data between the two controllers. Based on your reply from the comments, both the controllers belong to the same module.You can use $rootScope here to act as a common point.
As you can see, i've added $rootScope as a dependency in both the controllers and simply printed the txt variable in the second div.
JS Code
var app = angular.module('plunker', []);
app.controller('ACtrl', function($scope,$rootScope) {
$scope.name = 'This is Controller A ';
$scope.execute = function() {
alert('Executed!');
}
$rootScope.txt="Hi there from the other side";
});
app.controller('BCtrl', function($scope,$rootScope) {
$scope.name = 'This is Controller B ';
});
HTML
<div ng-controller="ACtrl">
<p>Hello {{name}}!</p>
</div>
<div ng-controller="BCtrl">
<p>Hello {{name}}!</p>
{{txt}}
</div>
Here is the DEMO
What I'd do is create a factory service that handles your HTTP requests, and then inject that service into your controllers... Code would look something like this:
var app = angular.module('sampleApp');
app.factory('sampleFactory', ['$http',
function($http) {
return {
getData: function(success, fail) {
if (_dataStore) {
success(_dataStore);
}
$http({
//fill in your params here
})
.then(
function successCallback(response) {
//store data in the _dataStore object
success(response)
}, fail(response))
},
_dataStore: {}
}
}
]);
app.controller('SampleACtrl', ['$scope', 'sampleFactory',
function($scope, sampleFactory) {
$scope.sampleA = sampleFactory.getData(success, fail);
}
]);
app.controller('SampleBCtrl', ['$scope', 'sampleFactory',
function($scope, sampleFactory) {
$scope.sampleB = sampleFactory.getData(success, fail);
}
]);
The main idea behind doing it like this is that you only make the HTTP request once, and then store the data in the factory as an object. When you call the getData() function on that object, you'll either get what is actually in the factory already (meaning the request was already made) or you'll go make the request. You'd pass in 2 functions (success or fail) as your response functions to the $http call. This is by far not 100% good, there's many improvements(add $q in there to return promises, etc) but it's a start in the right direction.
Long story short: USE FACTORIES!
Hello I am trying to fetch a single user from my mongoDB database.
I have a service that works like this:
The service:
app.service('UsersService', function($http, $routeParams) {
var getAllUrl = '/users';
this.getSingleUser = function() {
return $http.get(getAllUrl/$routeParams.firstname)
.then(function(response) {
return response.data;
})
}
});
And then I have the controller.
The controller:
app.controller('singleContactCtrl',
function($scope, UsersService, $routeParams) {
// Get single contact
UsersService.getSingleUser().then(function(data) {
$scope.singlecontact = data;
});
});
On my api when I do /users/firstname I get my json data. Is there something I am doing wrong? Using the resource is quite straight forward but I would like to get some more insight on how the $http works.
I think the problem is the url getAllUrl/$routeParams.firstname should be changed to getAllUrl + '/' + $routeParams.firstname