'undefined' getting appended to a specific Web API call - javascript

'Undefined' is getting appended to a specific WebAPI call in my angular application where as other calls succeed without issue.
Both registerUser and login call fails because of 'Undefined' character:
Request URL: http://localhost:25971/undefined/api/Account/Register
Request URL: http://localhost:25971/undefined/Token
Here is my code:
(function () {
"use strict";
angular
.module("userManagement")
.controller("mainCtrl", ["userAccount", mainCtrl])
function mainCtrl(userAccount) {
var vm = this;
vm.isLoggedIn = false;
vm.message = '';
vm.userData = {
userName: '',
email: '',
password: '',
confirmPassword: ''
};
vm.registerUser = function () {
vm.userData.confirmPassword = vm.userData.password;
userAccount.registration.registerUser(vm.userData, function (data) {
vm.confirmPassword = "";
vm.message = "...Registration successful";
// vm.login();
});
}
vm.login = function () {
vm.userData.grant_type = "password";
vm.userData.userName = vm.userData.email;
userAccount.login.loginUser(vm.userData, function (data) {
vm.isLoggedIn = true;
vm.password = "";
vm.message = "";
vm.token = data.access_token;
});
}
}
}());
Here is the code in userAccount factory method:
(function () {
"use strict";
angular.module("common.services")
.factory("userAccount", ["$resource", "appsettings", userAccount])
function userAccount($resource, appsettings) {
return {
registration: $resource(appsettings.serverPath + "/api/Account/Register", null,
{
'registerUser': { method: 'POST' }
}),
login: $resource(appsettings.serverPath + "/Token", null,
{
'loginUser': {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (data, headersGetter) {
var str = [];
for (var d in data) {
str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return str.join("&")
}
}
}
})
}
}
})();
Appsettings is defined like this:
(function () {
"use strict";
angular.module("common.services", ["ngResource"]).constant("appsettings", {
serverpath:"http://localhost:25879/"
});
}());
I am new to Angular and WebAPI, any help or direction to find the issue would be appreciated!

You appsettings constant should look like:
(function (angular) {
"use strict";
angular.module("common.services", ["ngResource"]).constant("appsettings", {
serverPath: "http://localhost:25879"
});
}(angular));
The property serverpath is not the same as serverPath and in you case serverPath is undefined. You should respect the casing.

Check for serverPath in apiSettings

Related

Is there any better way to display POST request in Angular Js

I have used both PUT and POST request to modify and create a data. But the thing is POST request is not working properly. When i click on add() button , automatically POST request is generating id in the json-data before filling the information in the text fields.
Moreover data should be updated when I click on the save() button . Below I have pasted my code, if I have made any mistake tel me know and I appreciate every one whomever gives any information.
HTMl :
<button class="btn btn-info" ng-click="addmode()"> Add </button>
<button class="btn btn-success" ng-show="editMode" ng-click="saveinfo()"> Save </button>
Angular JS :
$scope.addmode = function(information) {
var postinfo = information;
$http({
url:'http://localhost:3000/contacts' ,
method : 'POST',
data : postinfo
})
.then(
function successCallback(response) {
$scope.selectedcontact = '';
console.log(response.data)
},
function errorCallback(response) {
console.log("Error : " + response.data);
});
};
First create services/api.js
angular.module('app')
.factory('api', function ($rootScope,ApiEndpoint, $http, $q,$timeout,$cookies) {
var get = function (url) {
var config = {url: url, method: ApiEndpoint.Methods.GET};
return this.call(config);
};
var del = function (url) {
var config = {url: url, method: ApiEndpoint.Methods.DELETE};
return this.call(config);
};
var post = function (url, data) {
var config = {url: url, method: ApiEndpoint.Methods.POST, data: data};
return this.call(config);
};
var put = function (url, data) {
var config = {url: url, method: ApiEndpoint.Methods.PUT, data: data};
return this.call(config);
};
return {call: call, get: get, post: post, del: del, put: put};
});
After create service/apiendpoint.js
angular.module('app')
.constant('ApiEndpoint', {
ServerUrl: 'http://localhost/',
BaseUrl: 'http://localhost/',
Methods: {GET: 'GET', POST: 'POST', PUT: 'PUT', DELETE: 'DELETE'},
Models: {
test:"fe_api/test",
},
URLS: {
QUERY: 'app/'
},
getUrl: function (url) {
var host=window.location.host;
var protocol=window.location.protocol ;
return protocol+"//"+host+"/"+url;
}
});
**Create model handler **
angular.module('app')
.factory('ApiService', function (api, ApiEndpoint) {
var getModel = function (url_part)
{
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + url_part;
return api.get(url);
};
var getModelViaPost = function (url_part, data)
{
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + url_part;
return api.post(url, data);
};
var postModel = function(model_name, data) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name;
return api.post(url, data);
};
var putModel = function(model_name, data) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name;
return api.put(url, data);
};
var deleteModel = function(model_name, id) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name + '/' + id;
return api.delete(url);
};
return {
getModel: getModel,
postModel : postModel,
putModel : putModel,
deleteModel : deleteModel,
getModelViaPost : getModelViaPost
};
});
write API call in the controller
var data = {
wut_token: $cookies.data,
};
ApiService.postModel(ApiEndpoint.Models.test, data).then(function (response) {
if (response.SUCCESS == "FALSE") {
} else {
}
})

How to call nest factory in Angularjs?

Hi I am developing web application in angularjs. I have requirement below. I have one factory. I have added code snippet below.
myapp.factory('sadadpaymentapi', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', 'leaselisting', function ($http, $cookieStore, cfg, ScrollFunction, leaselisting) {
var sadadpaymentapiobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
var urlapi = baseurl + "api/ServiceRequest/CreateRSSedad/";
sadadpaymentapiobject.callsadad = function (PaymentType) {
leaselisting.leaselisting().then(function (response) {
//Problem in calling
}, function (error) { });
var request = {
url: urlapi,
method: 'POST',
data: {
SRActivityID: LoginID,
PaymentType: PaymentType,
PaymentAmount: "100"
},
headers: ScrollFunction.getheaders()
};
return $http(request);
}
return sadadpaymentapiobject;
}]);
Here is my second factory leaselisting
myapp.factory('leaselisting', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', function ($http, $cookieStore, cfg, ScrollFunction) {
var leaselistingobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
leaselistingobject.leaselisting=function(){
var requestObj = {
url: "api/ServiceRequest/GetROLSPSRLeaseList/",
data: {
LoginID: LoginID,
RSAccountNumber: $cookieStore.get("AccountNumber")
},
headers: ScrollFunction.getheaders()
};
$http(requestObj).then(function (response) {
}, function (error) {
});
}
return leaselistingobject;
}]);
I have found error in below line
leaselisting.leaselisting().then(function (response) { //Problem in calling
}, function (error) { });
May i am i doing anything wrong in the above code? May i know is it possible to call one factory from another? The response i get from leaselisting i want to pass it in callsadad function of sadadpaymentapi. So can someone hep me in the above code? I am getting error Cannot read property 'then' of undefined in the leaselisting.leaselisting().then(function (response) {},function(error){});
Also is there any way I can directly inject factory like payment amount: inject factory something like this?
I assume, that leaselistingobject.getValue is an asynchronous function.
So first of get your value :
leaselistingobject.getValue = function(){
var requestObj = {
url: "api/ServiceRequest/getValue/"
};
return $http(requestObj).then(function (response) {
return response.data;
});
}
And then use it. To let all async actions finish we use angulars $q.Here you can find a small tutorial.
myapp.factory('sadadpaymentapi', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', 'leaselisting', '$q',function ($http, $cookieStore, cfg, ScrollFunction, leaselisting, $q) {
var sadadpaymentapiobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
var urlapi = baseurl + "api/ServiceRequest/CreateRSSedad/";
sadadpaymentapiobject.callsadad = function (PaymentType) {
var leastListingPromise = leaselisting.leaselisting();
var getValuePromise = leaselisting.getValue();
$q.all([leastListingPromise, getValuePromise]).then(function (responses) {
//Here you have both responses in an array
var request = {
url: urlapi,
method: 'POST',
data: {
SRActivityID: LoginID,
PaymentType: PaymentType,
PaymentAmount: responses[1]
},
headers: ScrollFunction.getheaders()
};
return $http(request);
});
}
return sadadpaymentapiobject;
}]);
To make leaselisting() return the response of the request change the end of the function from
$http(requestObj).then(function (response) {
}, function (error) {
});
to
return $http(requestObj).then(function (response) {
return response.data;
}, function (error) {
});
If wont do anything about possible errors you can omit the error function part:
return $http(requestObj).then(function (response) {
return response.data;
});

Knockout JS Validation not working

I am a newbie in Knockout JS. i want to apply validations in KO. i have used plugin knockout.validation.min.js . I have implemented it like this but not working
My View Model
$(document).ready(function myfunction() {
ko.applyBindings(new EmployeeKoViewModel());
})
var EmployeeKoViewModel = function () {
var self = this;
self.EmpId = ko.observable()
self.Name = ko.observable("").extend({ required: { message: "please enter employee name " } });
self.City = ko.observable("").extend({ required: { message: "please enter employee city " } });
self.Employees = ko.observableArray();
//GetEmployees();
var EmpData = {
EmpId: self.EmpId,
Name: self.Name,
City: self.City,
};
function GetEmployees() {
$.ajax({
type: "GET",
url: "/Employee/About",
}).done(function (data) {
self.Employees(data);
}).error(function (ex) {
alert("Error");
});
}
self.save = function () {
var EmployeeKoViewModel.errors = ko.validation.group(self);
if (!EmployeeKoViewModel.errors().length <= 0) {
EmployeeKoViewModel.errors.showAllMessages();
return false;
}
$.ajax({
type: "POST",
url: "/Employee/Save",
data: ko.toJSON(EmpData),
contentType: "application/json",
success: function (data) {
self.EmpId(data.EmpId);
GetEmployees();
},
error: function () {
alert("Failed");
}
});
//Ends Here
};
}
I have created a fiddle it is working when i comment GetEmployees() method but not working with it
At this line
var EmployeeKoViewModel.errors = ko.validation.group(self);
you are trying to create a variable, but the syntax is like creating an object with a property which is of course invalid. In order to fix this you can initialize your object first:
var EmployeeKoViewModel = {};
EmployeeKoViewModel.errors = ko.validation.group(self);
if (!EmployeeKoViewModel.errors().length <= 0) {
EmployeeKoViewModel.errors.showAllMessages();
return false;
}
Here is a working jsFiddle

How to call web service in sencha touch 2?

I 'm beginner in sencha touch 2 and i need to call webservice.The code of web service is:
public function loginAction()
{
$request = $this->getRequest();
$username = $request->request->get('username');
$password= $request->request->get('password');
$success=false;
$token="error";
$error="test";
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserBy(array('username' => $username));
if (! $user)
{
$token="username not exists";
$success=false;
}
else
{
$password_user=$user->getPassword();
$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
$password = $encoder->encodePassword($password, $user->getSalt());
if ($password!=$password_user)
{
$token="password incorrect";
$success=false;
}
else
{
$token="logged";
$success=true;
}
}
$info= array("token" => $token);
$res=array("success"=> $success);
$res = array("status"=> $res,
"resultat"=>$info
);
$serializer = $this->get('jms_serializer');
$response = $serializer->serialize($res,'json');
return new Response($response);
}
and i make in project sencha a view: Login.js and a controller: Login.js. The problem is in calling the web service and the code in controller Login.js:
Ext.define('Sample.controller.Login', {
extend: 'Ext.app.Controller',
config: {
refs: {
loginView: 'loginview',
mainMenuView: 'mainmenuview'
},
control: {
loginView: {
signInCommand: 'onSignInCommand'
},
mainMenuView: {
onSignOffCommand: 'onSignOffCommand'
}
}
},
// Session token
sessionToken: null,
// Transitions
getSlideLeftTransition: function () {
return { type: 'slide', direction: 'left' };
},
getSlideRightTransition: function () {
return { type: 'slide', direction: 'right' };
},
onSignInCommand: function (view, username, password) {
console.log('Username: ' + username + '\n' + 'Password: ' + password);
var me = this,
loginView = me.getLoginView();
if (username.length === 0 || password.length === 0) {
loginView.showSignInFailedMessage('Please enter your username and password.');
return;
}
loginView.setMasked({
xtype: 'loadmask',
message: 'Signing In...'
});
Ext.Ajax.request({
url: 'http://localhost/dawinilastversion/web/app_dev.php/api/login',
method: 'post',
params: {
username: username,
password: password
},
success: function (response) {
var loginResponse = Ext.JSON.decode(response.responseText);
if (loginResponse.success === "true") {
// The server will send a token that can be used throughout the app to confirm that the user is authenticated.
me.sessionToken = loginResponse.sessionToken;
me.signInSuccess(); //Just simulating success.
} else {
me.signInFailure(loginResponse.message);
console.log('erreur.');
}
},
failure: function (response) {
me.sessionToken = null;
me.signInFailure('Login failed. Please try again later.');
}
});
},
signInSuccess: function () {
console.log('Signed in.');
var loginView = this.getLoginView();
mainMenuView = this.getMainMenuView();
loginView.setMasked(false);
Ext.Viewport.animateActiveItem(mainMenuView, this.getSlideLeftTransition());
},
singInFailure: function (message) {
var loginView = this.getLoginView();
loginView.showSignInFailedMessage(message);
loginView.setMasked(false);
},
onSignOffCommand: function () {
var me = this;
Ext.Ajax.request({
url: 'http://localhost/dawinilastversion/web/app_dev.php/api/login',
method: 'post',
params: {
sessionToken: me.sessionToken
},
success: function (response) {
// TODO: You need to handle this condition.
},
failure: function (response) {
// TODO: You need to handle this condition.
}
});
Ext.Viewport.animateActiveItem(this.getLoginView(), this.getSlideRightTransition());
}
});
And the web service login work with success:
you need to go one step deeper into the JSON response:
if (loginResponse.status.success === true)
and check against the bool true not the string true

Using a factory inside another factory AngularJS

I have a module...
angular.module('myModule', []);
And then a factory
angular.module('myModule')
.factory('factory1', [
function() {
//some var's and functions
}
]);
And then another factory
angular.module('myModule')
.factory('factory2', [
function() {
//some var's and functions BUT I want to use some var's from factory1
}
]);
But I want to use some variables from factory1 inside factory2, how can I inject factory1 into factory2?
This is what I would do:
On Factory One
angular.module('sampleApp')
.factory('factory1', function() {
var factory1 = {};
factory1.method1 = function () {
return true;
};
factory1.method2 = function () {
return "hello";
};
return factory1;
}
);
On Factory Two
angular.module('sampleApp')
.factory('factory2', ['factory1',
function(factory1) {
var factory2 = {};
factory2.method3 = function () {
return "bye vs " + factory1.method2();
};
return factory2;
}
]);
This is what i did and worked fine. Call SessionPresenters from Session
angular.module('tryme3App')
.factory('Session', function ($resource, DateUtils, SessionPresenters) {
return $resource('api/sessions/:id', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
data = angular.fromJson(data);
var result = SessionPresenters.get({id: data.id})
data.presenters = result;
return data;
}
},
'update': { method:'PUT' }
});
}).factory('SessionPresenters', function ($resource, DateUtils) {
return $resource('api/session.Presenters/:id', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET', isArray: true
},
'update': { method:'PUT' }
});
});

Categories

Resources