AngularJs dependency injection related to $http - angularjs

While writing the above code in AngularJs, I am getting an error :
Error: $injector:unpr
Unknown Provider
Unknown provider: $http
I believe the reason might be while injecting $http through the serviceProvider which in my case is httpServiceProviderFunction.$inject = ["$http"];. I would appreciate if anyone could help me understand these two questions:
1) Although I have injected the $http in the httpServiceProviderFunction. Why am I getting the above error?
2)Is there any way I can inject $http in the service directly without injecting in serviceProvider? In my example, it corresponds to this line:
function httpService(url, $http) {.....}
The code snippet can be found below:
(function() {
angular.module("httpServiceApp", []).controller("httpServiceController", httpServiceControllerFunction).provider("httpService", httpServiceProviderFunction).config(configObj);
configObj.$inject = ["httpServiceProvider"]
function configObj(httpServiceProvider) {
httpServiceProvider.configuration.baseUrl = "http://davids-restaurant.herokuapp.com/categories.json";
}
httpServiceProviderFunction.$inject = ["$http"];
function httpServiceProviderFunction($http) {
var provider = this;
provider.configuration = {
baseUrl: "http://davids-restaurant.herokuapp.com/categories.json"
}
provider.$get = function() {
var service = new httpService(provider.configuration.baseUrl, $http);
return service;
}
}
function httpService(url, $http) {
var service = this;
service.menuCategories = function() {
var response = $http({
method: "GET",
url: url
});
return response;
}
}
httpServiceControllerFunction.$inject = ["httpService"]
function httpServiceControllerFunction(httpService) {
var service = httpService;
var controller = this;
var promise = service.menuCategories();
promise.then(function(response) {
controller.categories = response.data;
}).catch(function(error) {
console.log("Error occured", error);
})
}
})();
<!DOCTYPE html>
<html ng-app="httpServiceApp">
<head>
<meta charset="utf-8">
<meta name="description" content="First Angular App">
<meta name="keywords" content="HTML, Javascript, AngularJs">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
<script src="app1.js"></script>
<title>HTTP service in AngularJs</title>
</head>
<body>
<div ng-controller="httpServiceController as controller">
<div>
<ul>
<li ng-repeat="items in controller.categories">({{items.short_name}}){{items.name}}</li>
</ul>
</div>
</div>
</body>
</html>
Thank you for your time. I appreciate your help.

Related

elasticsearch and angular js Interworking error

Hi i wondering that ploblem so i want ask somebody
so please give me solution?
I make html file like that photo
but when i open this html file this file not working…
any data not diplay
what is the ploblem in this html file?enter image description here
<!doctype html>
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<div ng-controller="QueryController">
</div>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/elasticsearch-browser/elasticsearch.angular.js"></script>
<script>
var myApp = angular.module('myApp', ['elasticsearch']);
// Create the es service from the esFactory
myApp.service('es', function (esFactory) {
return esFactory({ host: 'localhost:9200'});
});
myApp.controller('ServerHealthController', function($scope, es, esFactory) {
es.cluster.health(function (err, resp) {
if (err) {
$scope.data = err.message;
} else {
$scope.data = resp;
}
});
});
// We define an Angular controller that returns query results,
// Inputs: $scope and the 'es' service
myApp.controller('QueryController', function($scope, es, esFactory) {
// search for documents
es.search({
index: 'epowersyst',
type: 'logs',
body: {
query:
{
match_all : {} }
}
}).then(function (response) {
$scope.hits = response;
console.log($scope.hits)
alert("hits값 : " + response);
});
});
</script>
</body>
</html>

AngularJs with REST Api

i'm new to angularJs and want to learn more about it, i'm trying to display some users from a fake REST Api, when trying to run my code i got empty page and the console doesn't give me any errors , i don't know where is the error or where i can debug.
app.js
var myApp = angular.module("app", []);
contactsData.service.js look like that :
(function () {
var app = angular.module("app");
app.service("contactDataSvc", function ($http) {
var self = this;
self.getContacts = function () {
var promise1 = $http.get("http://localhost:3000/contacts");
var promise2 = promise1.then(function (response) {
return response.data;
});
return promise2;
}
});
})();
contacts.controller.js
(function () {
var myApp = angular.module("app");
myApp.controller("contactsCtrl", contactsCtrl);
function contactsCtrl(contactDataSvc) {
contactDataSvc.getContacts()
.then(function(data){
this.contacts = data;
});
}
})();
finally my view index.html
<html ng-app="app">
<head>
<title></title>
<script src="angular.js"></script>
<script src="app.js"></script>
<script src="contacts.controller.js"></script>
<script src="contactsData.service.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" />
<!--<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>-->
</head>
<body class="container">
<div>
<div ng-controller="contactsCtrl as ctrl">
<div class="raw">
<ul class="list-group">
<li class="li-group-item" ng-repeat="obj in ctrl.contacts">
{{obj.name.title + " " + obj.name.first + " " + obj.name.last}}
</li>
</ul>
</div>
</div>
</div>
</body>
</html>
Small correction required in your contactsCtrl
function contactsCtrl(contactDataSvc) {
var vm = this;
contactDataSvc.getContacts()
.then(function(data){
vm.contacts = data;
});
}
You cannot use this inside the then callback as the scope will be different.
Corrected working example here : http://plnkr.co/edit/LLKJipkBbiZ17QjQpw1X
Refer more:
https://www.w3schools.com/js/js_scope.asp
What is the scope of variables in JavaScript?
1 - Is this url correct? http://localhost:3000/contacts
2 - Open the url on any browser, does it return any response ? JSON?
Please check this first to see if the problem is not on the server side.
Firstly inject $scope in controller because anything/data that we want to access over Html from controller needs to be binded on $scope.
So you controller would look like:
(function () {
var myApp = angular.module("app");
myApp.controller("contactsCtrl", contactsCtrl);
function contactsCtrl($scope,contactDataSvc) {
contactDataSvc.getContacts()
.then(function(data){
$scope.contacts = data;
});
}
})();
Secondly from the service you need to return a promise from it only then you will be able to get the data once the response is back from the API.
So,the updated service code is :
(function () {
var app = angular.module("app");
app.service("contactDataSvc", function ($http,$q) {
var self = this;
var defered = $q.defer();
self.getContacts = function () {
var promise1 = $http.get("http://localhost:3000/contacts");
promise1.then(function (response) {
defered.resolve(response.data);
});
return defered.promise;
}
});
})();

Pulled out all my hair on an Angular unpr error

So I am getting an angular [$injector:unpr] error. Yes, I know what that normally means...I haven't defined something somewhere, or I am redefining the module over and over, or the like...but for the life of me I'm struggling to see the issue in my code.
I'm sure I'm missing something insanely basic, but after I've stared at code for a couple of hours, I go blind to it.
My HTML File:
<!DOCTYPE html>
<html ng-app="email">
<head>
<meta charset="UTF-8">
<title>Authentication</title>
<link href='https://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700' rel='stylesheet' type='text/css'/>
<meta content="width=device-width, initial-scale=1.0" name="viewport">
</head>
<body>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="node_modules/angular/angular.min.js"></script>
<div ng-controller="EmailAuthController as auth">
<h1>Authentication</h1>
<p>Request: [{{auth.request}}]</p>
<p>{{auth.response}}</p>
<p>{{1+2}}</p>
</div>
<script type="text/javascript" src="js/controllers/email.js"></script>
</body>
</html>
My email.js file (As you can see, I've commented out some stuff to try to isolate the issue):
/* global angular parseGet */
function parseGet(val) {
var result = '', // = "Not found",
tmp = [];
var items = location.search.substr(1).split('&');
for (var index = 0; index < items.length; index++) {
tmp = items[index].split('=');
if (tmp[0] === val) {
result = decodeURIComponent(tmp[1]);
}
}
return result;
}
(function () {
angular
.module('email', [])
.controller('EmailAuthController', [ '$scope','authFactory', function ($scope,authFactory) {
var vm = this,
req = parseGet('hash') || '';
vm.request = req;
// authFactory.validate(req)
// .then(function (response) {
// vm.response = response.data;
// });
}])
.factory('authFactory', [ '$rootScope', '$http', 'config', function ($rootScope, $http, config) {
var validate = function (hash) {
var url = config.SERVICE_URI + '/auth/email/' + hash;
return $http.get(url);
};
return {
validate: validate
};
}]);
})();
From the code you've given it appears config is not defined in your authFactory injection.
.factory('authFactory', [ '$rootScope', '$http', 'config', function(a, b, c) {} ]); // config is not defined

AngularJS call Rest Api: TypeError

I am calling restful service from AngularJS. HTML is very basic with a input text box and a button for query.
// basic.html
<!DOCTYPE html>
<html ng-app="cgApp" >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-resource.js"></script>
<script src="../js/controller.js"></script>
<script src="../js/service.js"></script>
</head>
<body>
<div ng-controller="CgseqCtrl">
<input ng-model="analysisid"><button ng-click="searchById()">Search</button>
<table>
<tr>
<td>{{seq.analysisId}}</td>
<td>{{seq.center}}</td>
<td>{{seq.diseaseAbbr}}</td>
<td>{{seq.filepath}}</td>
<td>{{seq.library}}</td>
</tr>
</table>
</div>
</body>
</html>
I use a service to call rest api
// service.js
app.factory("Cgseq", function ($http) {
// return $resource('http://localhost:8080/cgweb/api/seqs/fdebfd6e-d046-4192-8b97-ac9f65dc2009');
var service = {};
service.getSeqById = function(analysisid) {
return http.get('http://localhost:8080/cgweb/api/seqs/' + analysisid);
}
service.getSeq = function() {
return $http.get('http://localhost:8080/cgweb/api/seqs/fdebfd6e-d046-4192-8b97-ac9f65dc2009');
}
return service;
});
The function searchById() will be executed once the button is clicked. It is implemented in my controller.
// controller.js
var app = angular.module('cgApp', [])
app.controller('CgseqCtrl', ['$scope', 'Cgseq', function($scope, Cgseq){
$scope.searchById() = function() {
CgSeq.getSeqById($scope.analysisid)
.then(function(response){
$scope.seq = response;
});
}
}]);
When I load basic.html in a browser, even before I type in something in the input box and click the button, I got the following error:
angular.js:12416 TypeError: $scope.searchById is not a function
at new <anonymous> (controller.js:8)
You should remove the () from $scope.searchById() = function
And correct the typo (case-sensitivity) for Cgseq
I.e.:
$scope.searchById = function() {
Cgseq.getSeqById($scope.analysisid)
.then(function(response){
$scope.seq = response;
});
}

access POST data from httpBackend in e2e test

In this example, I have an e2e test doing a button click, which executes a function that does a POST
I would like to be able to have access to the "data" object from testDev httpBackend callback, in my e2e scenerios code, for verification.
Is this possible in an e2e test? If so, could you point me in the right direction?
thanks
scenerio code
describe('test2 app', function() {
beforeEach(function() {
browser().navigateTo('/testbed/e2e/app/index2.html');
});
it('should run a POST',function() {
element('#myButton2').click();
});
});
test module
var test2Dev = angular.module('test2Dev', ['test2App', 'ngMockE2E'])
.run(function($httpBackend) {
$httpBackend.whenPOST(/testpost/)
.respond(function(method, url, data, headers){
console.log(data);
return [200, data, {}];
});
});
markup
<html lang="en" ng-app="test2Dev" ng-controller="test2Ctrl">
<head>
<meta charset="utf-8">
<title>Test click </title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-mocks.js"></script>
<script src="/testbed/e2e/test/e2e/test2Dev.js"></script>
<script src="js/controllers2.js"></script>
</head>
<body>
<button id="myButton2" ng-click="runPost()">run post</button>
</body>
</html>
controller
var test2App = angular.module('test2App', []);
test2App.controller('test2Ctrl', function($scope,$http) {
$scope.runPost = function() {
$http.post('/testpost',{
data1 : 'chevy',
data2 : 'ford'
});
}
});
runner
<!doctype html>
<html lang="en">
<head>
<title>End2end Test Runner</title>
<meta charset="utf-8">
<base href="../..">
<script src="app/lib/angular/angular-scenario.js" ng-autotest></script>
<script src="app/lib/angular/angular-mocks.js" ng-autotest></script>
<script src="/testbed/e2e/test/e2e/test2Dev.js"></script>
<script src="/testbed/e2e/test/e2e/scenarios2.js"></script>
</head>
<body>
</body>
</html>
Not very pretty but I removed my test module, and used a changed version of "mockApi" here->
https://github.com/blabno/ngMockE2E-sample (thank you Bernard Labno)
changed e2e.mocks.js to add the data object to it's config obj->
function setup(method, url, config)
{
$httpBackend.when(method, url).respond(function (requestMethod, requestUrl, data, headers) {
config.triggered = true;
config.data = data;
var response = config.response || {};
if (config.serverLogic) {
response = config.serverLogic(requestMethod, requestUrl, data, headers);
}
return [response.code || 200, response.data];
});
}
setup(POST, /testpost/, mocks.api.post_test);
.... and added this method to access it....
chain.getData = function() {
return this.addFuture("get data object for " + itemName, function(done) {
done(null,JSON.parse(api[itemName].data));
});
};
... here is my scenerio now...
it('should run a POST',function() {
element('#myButton2').click();
expect(mockApi("post_test").getData()).toEqual({
data1 : 'chevy',
data2 : 'ford'
});
});
Is there a better way to do this?

Resources