studentService.js
app.factory('saveStudentService',['$http','$scope',function ($http,$scope) {
var studentData = {};
studentData.save = function(jsondata){
var action = "student";
var method = "POST";
$http({
url: action,
method: method,
headers: {'Content-Type': 'application/json'},
data: jsondata
}).success(function(data, status, headers, config) {
toastr.success(status +' : Data has been submitted successfully ');
}).error(function(data, status, headers, config) {
toastr.error(status + ' : Data has not been submitted successfully ');
});
};
return studentData;
}]);
I am getting this error
angular.js:13642Error: [$injector:unpr] http://errors.angularjs.org/1.5.6/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20saveStudentService
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:6:412
If from studentService.js, $scope is being removed, i.e
app.factory('saveStudentService',['$http',function ($http) {
this code is working properly, and not getting any error message in console.
Following is the studentController.js file from where this studentService is being called.
StudentController.js
app.controller('saveStudentCtrl',['$scope', 'saveStudentService', function($scope,saveStudentService) {
$scope.submit_create_student = function() {
var jsondata = $scope.student;
saveStudentService.save(jsondata);
}
}]);
but if same thing i.e $scope is being added in the updateStudentService then this code is working as expected.
app.controller('updateStudentCtrl',['$scope','retriveStudentService', 'updateStudentService', function($scope,retriveStudentService, updateStudentService) {
$scope.getStudentDataFromServer = function() {
retriveStudentService.get();
};
$scope.submit_update_student = function(e) {
updateStudentService.update();
}
}]);
Could someone please clarify, what is happening here. Though able to use same thing in one place, but not able to use same process at someother place.
You cannot inject scope into services. You can inject it to controllers.
Related
I have the following controller and service
angular
.module('myApp')
.controller('Spliptter', Spliptter) // Controller
.service('SplitService', SplitService); //Service
function Spliptter($scope, SplitService){
var result = SplitService.phoeNoSplit($scope.phoneNumber.number); //Phone Data
$scope.area: result['area'];
$scope.country: result['country'];
}
function SplitService() {
this.phoeNoSplit = function(phoneNumber) {
var area = phoneNumber.substring(0, 3); //Info that I want to send
var country = phoneNumber.substring(3, 10); //Parse
return {
'area': area,
'country': country
}
}
}
Also I have a form where I use to send the area code and the country code.
angular //Controller of the form that i'm using to send the area and country code
.module('myApp')
.controller('formController', formController); // Form controller
function formController($scope, $http, $rootScope) {
$scope.SendFormController = function () {
$http({
method:'POST',
url:myURL.com,
data : {
ciaPhone: $scope.TokenResponse.datos.ciaPhone,
phoneCountry: $scope.country,
phoneArea: $scope.area
}
}, // form fields
headers: {
'Content-Type': 'application/json'
}//
})
.success(function ( data, status, headers) {
$rootScope.datosPersonales = data;
})
.error(function (data, status, header, config) {
}; //
}
But, I dont know whats the problem. I'm new in angular.
Please read angular docs first so that you will get better understanding how controller and service works.
Here issue is you are trying to access the scope of Spliptter controller into formController controller which will never possible.
If you have to use that scope values in formController then you will have to initialise those scope values in formController itself.
Refer below code:
formController
angular //Controller of the form that i'm using to send the area and country code
.module('myApp')
.controller('formController', formController); // Form controller
function formController($scope, $http, $rootScope, SplitService) {
var result = SplitService.phoeNoSplit($scope.phoneNumber.number);
$scope.area: result['area'];
$scope.country: result['country'];
$scope.SendFormController = function () {
$http({
method:'POST',
url:myURL.com,
data : {
ciaPhone: $scope.TokenResponse.datos.ciaPhone, // am not sure from where you are getting it
phoneCountry: $scope.country,
phoneArea: $scope.area
}
}, // form fields
headers: {
'Content-Type': 'application/json'
}//
})
.success(function ( data, status, headers) {
$rootScope.datosPersonales = data;
})
.error(function (data, status, header, config) {
}; //
}
I'm trying to set data to controller using my service viewShare, when i look to my console i can see the console.log of controller coming first and undefined but the services started first the strange is after this console.log, i can see the console.log from viewShare populated. If i try the function in controller again then my controller is populated correctly.
my controller:
$scope.getLine = function(search){
arcTouchAPI.getLine(search);
console.log(viewShare.getDetails);
$scope.details = viewShare.getDetails.details; //angular ignores my viewShare call and go to console.log($scope.details) than it start the viewShare service
$scope.$apply;
console.log($scope.details);
};
my service API:
var _getLine = function(search){
var encoded = $base64.encode("xxxx:xxxx");
$http({
url: "https://api.appglu.com/v1/queries/findRoutesByStopName/run",
headers : {
"X-AppGlu-Environment":"xxxx",
"Authorization": "Basic "+encoded,
"Content-Type" : "application/json; charset=utf-8"
},
method: 'POST',
data: {
"params":{
"stopName": "%"+search+"%"
}
}
}).then(function(response){
viewShare.add(response.data.rows);
// console.log($rootScope.details + "details");
console.log(response.data.rows);
});
}
return {
getLine : _getLine
}
});
my service to share data between views:
angular.module('myApp').factory('viewShare', function viewShare() {
var messages={};
var _add = function(message){
messages.details = "";
messages.details=message;
console.log(messages.details);
return messages.details;
};
var _getDetails = function(){
return messages;
};
return{
getDetails: messages,
add: _add
}
});
$http call is non-blocking, which means that your console.log is executed straight after your request is sent to getLine (as coded), however this does not wait for the $http call to finish, and therefore has no data right away. You should return the $http promise from _getLine, and wait for the promise to resolve, before trying to getDetails. Furthermore, an explicit call to $scope.$apply is not necessary.
var _getLine = function(search){
var encoded = $base64.encode("xxxx:xxxx");
return $http({ // add return statement here to return a promise
url: "https://api.appglu.com/v1/queries/findRoutesByStopName/run",
headers : {
"X-AppGlu-Environment":"xxxx",
"Authorization": "Basic "+encoded,
"Content-Type" : "application/json; charset=utf-8"
},
method: 'POST',
data: {
"params":{
"stopName": "%"+search+"%"
}
}
}).then(function(response){
viewShare.add(response.data.rows);
// console.log($rootScope.details + "details");
console.log(response.data.rows);
});
}
Change controller to:
$scope.getLine = function(search){
arcTouchAPI.getLine(search).then(function(){
console.log(viewShare.getDetails);
$scope.details = viewShare.getDetails.details;
});
};
I have an angular controller with an http.post request but I'm not getting response, the service works fine because a test it using postman.
I need to display the data from the WS in an HTLM table(I know how to do this part) when the page is loaded, I'm sendinng the body for the request in a variable name "data", the header configuration un a variable name "config" and the the http.post call to the URL of my WS.
I'm new to angular so I don't know if I'm missing something, also I want to print the response in the console to test if it's returnig what I'm expecting.
I took this code from an example I found on the web and I modify it, in the example there's a button where the call to SendData() function but I don't need a button, the call has to be made as the page is loaded.
This is the controller code
.controller("HttpGetTestController", function ($scope, $http) {
$scope.SendData = function () {
var data = {
"userId":"mdrodri",
"token":"840430482834947828876768058086529370654",
"domain":"MX",
"filters":{
"timeFrameType":"Week (FiscalYear)",
"custMembSelectionType":"TOTAL",
"locationSelectionType":"Country",
"merchandiseSelectionType":"SBU",
"startYear":"2015",
"endYear":"2015",
"startUnit":"1",
"endUnit":"1",
"comparator":false,
"locationSelections":["CA"],
"merchandiseSelections":["SBU38"],
"custMembSelections":["TOTAL"],
"metricSelections":["Product Sales (Category Rank)"],
"rankOrder":"10"
},
"additionalFilters":[],
"cache":false
};
var config = {
headers : {
'Content-Type': 'application/json;'
}
}
$http.post('http://whateverurl/', data, config)
.success(function (data, status, headers, config) {
$scope.PostDataResponse = data;
console.log("Success");
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
console.log("Data: " + data);
console.log("Status: " + status);
console.log("Headers: " + header);
console.log("Config: " + config);
});
};
})
In my HTML this is how I'm calling that controller
<div class="panel panel-default" ng-controller="HttpGetTestController">
Thank's for the time and help.
You need to call $scope.SendData() function in the controller :
.controller("HttpGetTestController", function ($scope, $http) {
$scope.SendData = function () {
//your code ...
}
//then the calling
$scope.SendData();//here
}
I'm trying to read a properties file in angular, It's neccesary to have this file at the root of my project without any kind of angular stuffs, just a simple file, like java.
This is what I'm doing.
Creating a angular.properties file.
angular.properties
{
"url": "http://localhost"
}
This is my controller where I invoke my service method:
controller
captchaService
.all()
.then(function(data) {
...
}, function (data) {
...
});
This is my service class:
service
'use strict';
angular.module('app.service', [])
.factory('myService',
['$http', '$q',
function ($http, $q) {
var _URL = "";
function getValuesFromProperties() {
$http({
method : 'GET',
url : 'angular.properties'
}).success(function (data, status, headers, config) {
_URL = data.url;
}).error(function (data, status, headers, config) {
...
});
}
function all() {
getValuesFromProperties();
var deferred = $q.defer(),
promise = deferred.promise;
sessionStorage.removeItem('X_CAPTCHA_TOKEN');
$http({
method : 'POST',
url : _URL
}).success(function (data, status, headers, config) {
...
}).error(function (data, status, headers, config) {
...
});
return promise;
}
return {
all : all,
getValuesFromProperties : getValuesFromProperties
};
}]);
But here in my services class I have two $http running on an asynchronous way for that reason I can not get the value of url everything else works perfect. How can resolve this? Maybe there is another way to do this. I don't want to create a constant class because this file it's placed at the root of the project and it will be configure for others, they don't need to enter inside a lot of folders and check the code, search and edit. Any idea?
Problems with the implementation of POST request (angularjs ($http))
I am trying to perform a POST request, but get the following error:
Error: Unexpected request: POST http://192.168.88.54:3000
No more request expected
at $httpBackend (file:///Users/vasyasemenov/workspace/tamua/ogogo-frontend/build/vendor/angular-mocks/angular-mocks.js:1176:9)
at sendReq (file:///Users/vasyasemenov/workspace/tamua/ogogo-frontend/build/vendor/angular/angular.js:7721:9)
at serverRequest (file:///Users/vasyasemenov/workspace/tamua/ogogo-frontend/build/vendor/angular/angular.js:7455:16)
at wrappedCallback (file:///Users/vasyasemenov/workspace/tamua/ogogo-frontend/build/vendor/angular/angular.js:10696:81)
at wrappedCallback (file:///Users/vasyasemenov/workspace/tamua/ogogo-frontend/build/vendor/angular/angular.js:10696:81)
at file:///Users/vasyasemenov/workspace/tamua/ogogo-frontend/build/vendor/angular/angular.js:10782:26
at Scope.$eval (file:///Users/vasyasemenov/workspace/tamua/ogogo-frontend/build/vendor/angular/angular.js:11697:28)
at Scope.$digest (file:///Users/vasyasemenov/workspace/tamua/ogogo-frontend/build/vendor/angular/angular.js:11525:31)
at Scope.$apply (file:///Users/vasyasemenov/workspace/tamua/ogogo-frontend/build/vendor/angular/angular.js:11803:24)
at HTMLButtonElement.<anonymous> (file:///Users/vasyasemenov/workspace/tamua/ogogo-frontend/build/vendor/angular/angular.js:17690:21)
My implementation of the POST request:
angular.module('App')
.config(['$httpProvider',
function($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
}
])
.service('API', function API($http, $q, PROD, PROD_HOST, DEV_HOST, API_TOKEN) {
var self = this;
self.host = (PROD ? PROD_HOST : DEV_HOST);
self.performRpcCall = {
post: function(url, params) {
var deferred = $q.defer();
var data = {
jsonrpc: '2.0',
params: params,
method: url
};
$http.post(self.host, data).success(function(data) {
if(data.result) {
deferred.resolve(data.result);
}else{
deferred.reject(data.error);
}
}).error(function(data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
}
};
self.registerUser = function(params) {
params.token = API_TOKEN;
return self.performRpcCall.post('/api/users', params);
};
});
Where is the error? Thank you
Not sure if this is the problem or not but I've had trouble before when passing an object as the data parameter to $http.post before.
To correct that I've used jQuery's $.params(data) in the past or...
data = {
someVar : someVal,
anotherVar : anotherVal
};
return $http({
method : 'POST',
url : 'someURL/path/to/api/script',
params : data,
headers : {'Content-Type' : 'application/x-www-form-urlencoded'}
}).success(function(response){
return (angular.isDefined(response.data.result)) ? response.data.result : response.data.error;
}).error(function(response){
return { data : response.data, status : response.status };
});
data gets JSONified for the params var when passing $http a configuration object. Of course you already set the header with the provider. There is also a data config property, I haven't used that but I think it does the same but just doesn't JSONify the data into a string but rather incorporates it into the header as message data.