How to interact between 2 config files - javascript

I have a config.prop file which is being called from ngConfig.js file which is a service file. This prop file contains an URL which I need in my 2nd service file ngContent.js .
These files are being called individually from resolve.
$routeProvider.
when('/login', {
templateUrl: 'views/login.html',
controller: LoginController,
resolve: {
urlData: function(Config) {
return Config.prop().then(function(response) {
return response;
});
},
contentData:function(Content){
return Content.prop().then(function(response){
return response;
});
}
}
})
The response I am getting from urlData, which is resolving my response from ngConfig.js is the content of the config.prop. I need this response in my ngContent.js file.
The content of ngConfig.js is
angular.module('ngConfig', [])
.service('Config', function ($http, $rootScope, $document) {
//API calling method for all method
this.prop = function () {
try {
//API calling
var promise = $http({
method: 'GET',
dataType: "application/json",
data: 'json',
cache: false,
url: 'config.prop',
}).then(function (response) {
return response;
}, function (response) {
return response;
});
} catch (ex) {
return ex;
}
return promise;
};
});
The content of ngContent.js is
angular.module('ngContent', [])
.service('Content', function ($http, $rootScope, $document) {
//API calling method for all method
this.prop = function () {
try {
//API calling
var promise = $http({
method: 'GET',
dataType: "application/json",
data: 'json',
cache: false,
url: API_URL
}).then(function (response) {
return response;
}, function (response) {
return response;
});
} catch (ex) {
return ex;
}
return promise;
};
});
The API_URL is present in config.prop file, which is called from ngConfig.js file.
I hope I was able to present my problem clearly.
Thanks in advance.

You may pass urlData to contentData, like this, and then pass it to Content.prop().
contentData: function(Content, urlData){
return Content.prop(urlData).then(function(response){
return response;
});
}
Edit
This doesn't work with $routeProvider, you have to use $stateProvider of ui-router.
I have used it and it works. Use it the same way as discussed above.

Related

How to chain multiple separate JavaScript functions

I know similar questions have been asked before but none of the examples make sense to me. (Any I have found have failed to explain the basics for me with the clarity I need.)
I have four AngularJS functions. Each calls a REST service and does stuff that is unrelated to any of the other functions. E.g.
$scope.step1 = function() { $http({
method: 'GET',
url: "http://www/end/point",
cache: true,
headers: { "Accept": "application/jsonp;odata=verbose" }
}).success(function (data, status, headers, config) {
$scope.step1data = data;
}).error(function (data, status, headers, config) {
$scope.logError(data);
});};
I would like to call the four functions in sequence
$scope.step1
$scope.step2
$scope.step3
$scope.step4
And catch any errors encountered.
I have narrowed the code to the below but it does not work for me. Any help would be greatly appreciated.
$scope.step1().then(function() {
$scope.step2();
}).then(function() {
$scope.step3();
}).then(function() {
$scope.step4();
}).catch(function(e) {
console.log(e);
});
You need to return the promise from each step function to your then() callback so that its resulting promise waits for that promise:
$scope.step1().then(function() {
return $scope.step2();
})...
First, change your step1, step2, step3 and step4 to return promises like below:
$scope.step1 = function() {
return $http({
method: 'GET',
url: "http://www/end/point",
cache: true,
headers: { "Accept": "application/jsonp;odata=verbose" }
})};
$scope.step2 = function() {
return $http({
method: 'GET',
url: "http://www/end/point",
cache: true,
headers: { "Accept": "application/jsonp;odata=verbose" }
})};
$scope.step3 = function() {
return $http({
method: 'GET',
url: "http://www/end/point",
cache: true,
headers: { "Accept": "application/jsonp;odata=verbose" }
})};
$scope.step4 = function() {
return $http({
method: 'GET',
url: "http://www/end/point",
cache: true,
headers: { "Accept": "application/jsonp;odata=verbose" }
})};
Then, chain them together like this:
$scope.step1().then(function (step1data) {
$scope.step1data = step1data;
$scope.step2().then(function (step2Data) {
$scope.step2Data = step2Data;
$scope.step3().then(function (step3Data) {
$scope.step3Data = step3Data;
$scope.step4().then(function (step4Data) {
$scope.step4Data = step4Data;
});
});
});
})
You can mix asynchronous functions with any kind of logic that JavaScript offers if you execute your code synchronously via nsynjs. Here is how your code may need to be transformed:
Step 1: Wrap asynchronous function into generic nsynjs-aware wrapper:
// generic function to retrieve url
// ctx is a reference to caller pseudo-thread context
var httpUrl = function(ctx,url,$http) {
var res={};
$http({
method: 'GET',
url: url,
cache: true,
headers: { "Accept": "application/jsonp;odata=verbose" }
})
.success(function (data, status, headers, config) {
res.data = data;
ctx.resume() // tells nsynjs to resume caller function
}).error(function (data, status, headers, config) {
ctx.resume(data) // resume caller function with exception
// or replace with these 2 lines if you don't want exception
// res.error = data;
// ctx.resume()
});
return res;
};
getUrl.nsynjsHasCallback = true; // this tells nsynjs engine that it
// should pause execution and wait until ctx.resume() is called from callback
Step 2. Write your logic as if it was synchronous, and put it into function:
function synchronousCode(param1, param2) {
var step1 = function() {
var data = httpUrl(nsynjsCtx,"nsynjs/examples/data/file1.json").data;
console.log("data is ready at this point:",data);
// do staff this data
return data;
};
var step2 = function() {
var data = httpUrl(nsynjsCtx,"nsynjs/examples/data/file2.json").data;
console.log("data is ready at this point:",data);
// do staff this data
return data;
};
console.log( step1(param1) + step2(param2) ); // do more staff with data
}
Step 3. Run your synchronous code via nsynjs:
nsynjs.run(synchronousCode,{},"value for param1","value for param1",function(){
console.log("Synchronous Code done");
})
More examples here: https://github.com/amaksr/nsynjs/tree/master/examples
You need to use promise, in your controller, you should inject $q which will handle promise.
angularApp.controller('YourController', ['$q', '$scope',
function ($q, $scope) {
$scope.firstFunction = function () {
var deferred = $q.defer();
//Do things you want here...
console.log(1);
deferred.resolve();
return deferred.promise;
};
$scope.secondFunction = function () {
var deferred = $q.defer();
//Do things you want here...
console.log(2);
deferred.resolve();
return deferred.promise;
};
$scope.firstFunction().then(function () {
$scope.secondFunction.then(function () {
console.log(3)
})
})
}]);
console logs in functions above will print out:
1
2
3

Factory function not returning data

I have an angularjs factory to get data via $http.get():
'use strict';
app.factory('apiService', ['$http', function ($http) {
var apiService = {};
apiService.urlBase = 'http://localhost:1337/api/';
apiService.get = function (urlExtension) {
$http({
method: 'GET',
url: apiService.urlBase + urlExtension
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
console.log(response);
});
}
return apiService;
}]);
The problem is, that it always returns undefined when i call the method apiService.get(); in a Controller. When I log the response data in the factory, it display the right data. The apiService.urlBase variable is always filled in my controller.
Do you guys have any suggestions or am I doing something wrong? Maybe it's a syntax error.
You are not returning the promise that is returned by $http. Add return before $http
Okay I solved the problem. I just passed a callback function via parameter for my get() function.
'use strict';
app.factory('apiService', ['$http', function ($http) {
var apiService = {};
apiService.urlBase = 'http://localhost:1337/api/';
apiService.get = function (urlExtension, callback) {
var data = {};
$http({
method: 'GET',
url: apiService.urlBase + urlExtension
}).then(function successCallback(response) {
data = response.data;
callback(data);
}, function errorCallback(response) {
console.log(response);
});
return data;
}
return apiService;
}]);

Angular js .then is not a function

I have this service that loads data..
angular.module('App').service('daysService', ['$http','$q',function($http,$q) {
var days = [];
return {
loadDay: function() {
$http({
method: 'get',
url: '/app/days/list/',
}).success(function(data) {
days.push(data);
return days;
}).error(function (data) {
console.log('Error checking server.');
});
}
};
}]);
than in the controller i call the service
daysService.loadDay.then(function(data) {
alert(data)
});
But i'm getting this error TypeError: daysService.loadDay.then is not a function
Any suggestion?
You are not returning anything from your loadDay function. Try this:
return {
loadDay: function() {
return $http({ // <-- return the promise
method: 'get',
url: '/app/days/list/',
}).success(function(data) {
days.push(data);
return days;
}).error(function (data) {
console.log('Error checking server.');
});
}
};
daysService.loadDay.then(function(data) {
alert(data)
});
On the first line you are not calling loadDay like a function you are accessing it as a property. so you need to change it to this:
daysService.loadDay().then(function(data) {
alert(data)
});
Note the parenthesis on loadDay.
Secondly, you are using a service like a factory. So you have two options:
angular.module('App').service('daysService', ['$http','$q',function($http,$q) {
var days = [];
this.loadDay = function() {
$http({
method: 'get',
url: '/app/days/list/',
}).success(function(data) {
days.push(data);
return days;
}).error(function (data) {
console.log('Error checking server.');
});
};
}]);
OR
angular.module('App').factory('daysService', ['$http','$q',function($http,$q) {
var days = [];
return {
loadDay: function() {
$http({
method: 'get',
url: '/app/days/list/',
}).success(function(data) {
days.push(data);
return days;
}).error(function (data) {
console.log('Error checking server.');
});
}
};
}]);
Finally, you aren't returning the promise from the function:
function() {
return $http({
method: 'get',
url: '/app/days/list/',
}).success(function(data) {
days.push(data);
return days;
}).error(function(data) {
console.log('Error checking server.');
});
};
And if I were doing this, I would do:
angular.module('App').factory('daysService', ['$http', '$q', function($http, $q) {
var days = [];
this.loadDay = function() {
return $http.get('/app/days/list/').then(
function(data) {
days.push(data);
return days;
},
function(data) {
console.log('Error checking server.');
}
);
};
}]);
Your factory should return a promise instead of days if you want to use .then(). I believe you can do something like return $q.when(days) instead of return days and that should work.
Also just to note, .success() and .failure() callbacks are deprecated as of Angular 1.4. Not sure which version you're using, but $http now uses .then following this pattern:
$http({stuff}).then(function successCallback(response) {
//success
}, function errorCallback(response) {
// error
});
angular.module('App').service('daysService', ['$http','$q',function($http,$q) {
var days = [];
return {
loadDay: function() {
$http({
method: 'get',
url: '/app/days/list/',
}).success(function(data) {
days.push(data);
//return days;
}).error(function (data) {
console.log('Error checking server.');
});
},getDays: function(){ return days; }
};
}]);
daysService.loadDay(); $window.alert(daysService.getDays());
If you create a promise only then will you be able to use it with .then(). Check this document on how to create a promise. It is simple. https://docs.angularjs.org/api/ng/service/$q
You code is right now incapable of using .then() and the object/object property is not present so the error TypeError: daysService.loadDay.then is not a function. Else write a code that does not require you to use .then() but can work as normally triggered functions. That will work too.
/* In your service */
angular.module('App').factory('daysService', ['$http',function($http) {
var days = [];
return {
loadDay: function() {
$http({
method: 'get',
url: '/app/days/list/',
}).success(function(data) {
days.push(data);
return days;
}).error(function (data) {
console.log('Error checking server.');
return;
});
}
};
}]);
/* In your controller trigger the eventorclick */
$scope.trigger = function(){
$scope.modelname = daysService.loadDay(); /* returns days else undefined or null */
alert($scope.modelname); /* handle your issues if you have array of objects */
}

Consume AngularJS service from simple javascript

I have a main.js javascript file that has an init() function in.
I also have this AngularJS service:
(function () {
var app = angular.module('spContact', ['ngRoute']);
app.factory('spAuthService', function ($http, $q) {
var authenticate = function (userId, password, url) {
var signInurl = 'https://' + url + '/_forms/default.aspx?wa=wsignin1.0';
var deferred = $q.defer();
var message = getSAMLRequest(userId, password, signInurl);
$http({
method: 'POST',
url: 'https://login.microsoftonline.com/extSTS.srf',
data: message,
headers: {
'Content-Type': "text/xml; charset=\"utf-8\""
}
}).success(function (data) {
getBearerToken(data, signInurl).then(function (data) {
deferred.resolve(data);
}, function (data) {
deferred.reject(data)
})
});
return deferred.promise;
};
return {
authenticate: authenticate
};
function getSAMLRequest(userID, password, url) {
return 'envelope';
}
function getBearerToken(result, url) {
var deferred = $q.defer();
var securityToken = $($.parseXML(result)).find("BinarySecurityToken").text();
if (securityToken.length == 0) {
deferred.reject();
}
else {
$http({
method: 'POST',
url: url,
data: securityToken,
headers: {
Accept: "application/json;odata=verbose"
}
}).success(function (data) {
deferred.resolve(data);
}).error(function () {
deferred.reject();
});
}
return deferred.promise;
}
});
})();
How can I call this services "authenticate" method from the init() function of my main JavaScript file?
This service should return some authentication cookies that I would need for data querying.
You need to inject this factory to some controller/directive like:
app.controller('MyCtrl', ['spAuthService', function (spAuthService) {
spAuthService.authenticate.then(function (data) {
// ...
});
}]);
And this controller MyCtrl may be put on some home page and bootstrapped by Angular automatically.

Angular Service - Return http response

I'm trying to build an angular service I can reuse for doing my http requests etc. This all works when it's not in a service.
The following code works and does the login, but the log of $scope.data is always undefined. If i put a log in on the success before I return data it returns the data, but not back to the controller which is what i'm really looking to do.
Just for clarification, I want to be able to access the json data returned from the server as 'data' in the success in my controller.
//App.js
.service('SaveSubmitService', function ($http, $log) {
this.addItem = function(url, options){
var xsrf = $.param({
Username: options.Username,
Password: options.Password
});
$http({
method: 'POST',
url: url,
data: xsrf,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data, status, headers, config) {
return data;
}).
error(function(data, status, headers, config) {
console.log(data);
return false;
});
}
})
Controller:
.controller('LoginCtrl', function ($scope, $stateParams, $location, $ionicLoading, $http, SaveSubmitService, $log) {
if (localStorage.getItem("SessionKey")) {
$location.path('home');
}
$scope.login = {};
$scope.doLogin = function doLogin() {
$scope.data = SaveSubmitService.addItem('http://*****/Services/Account.asmx/Login', $scope.login);
$log.info($scope.data);
};
})
First of all make SaveSubmitService return promise object. Then use its API to provide a callback to be executed once data is loaded:
.service('SaveSubmitService', function ($http, $log) {
this.addItem = function (url, options) {
var xsrf = $.param({
Username: options.Username,
Password: options.Password
});
return $http({
method: 'POST',
url: url,
data: xsrf,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response) {
return response.data;
})
.catch(function(error) {
$log.error('ERROR:', error);
throw error;
});
}
});
And the you will use it like this in controller:
$scope.doLogin = function doLogin() {
SaveSubmitService.addItem('http://*****/Services/Account.asmx/Login', $scope.login).then(function(data) {
$scope.data = data;
$log.info($scope.data);
});
};
Note, how you return result of $http function call, it returns Promise which you use in controller.
saveSubmitService Service method is returning promise and it can be resolved using .then(function())
Your controller code will look like below.
CODE
$scope.doLogin = function doLogin() {
var promise = saveSubmitService.addItem('http://*****/Services/Account.asmx/Login', $scope.login);
promise.then(function(data) {
$scope.data = data
});
};
Thanks
.factory('SaveSubmitService', function ($http, $log) {
return{
getData:function(url,xsrf)
{
$http({
method: 'POST',
url: url,
data: xsrf,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data, status, headers, config) {
return data;
}).
error(function(data, status, headers, config) {
console.log(data);
return false;
});
}
}
})
.controller('LoginCtrl', function ($scope, $stateParams, $location, $ionicLoading, $http, SaveSubmitService, $log) {
if (localStorage.getItem("SessionKey")) {
$location.path('home');
}
$scope.login = {};
$scope.doLogin = function doLogin() {
$scope.data = SaveSubmitService.addItem(, );
$log.info($scope.data);
};
SaveSubmitService.getData('http://*****/Services/Account.asmx/Login',$scope.login).success(function(data,status){
$scope.data
}).error(function(data,status){ });
)};

Categories