How to pass an object to AngularJS factory? - javascript

I am in edit state i am trying to update riskDto but i am getting an error about some object i dont know what i am doing wrong please help.
Code tried so far...
ctrl.js
RiskService.saveAllignRiskToProcess($scope.riskDTO,$stateParams.processKey).then(function (response) {
if ($scope.editMode) {
$scope.hideYesBtn = true;
$scope.hideNoBtn = true;
$scope.showOkBtn = true;
$scope.messageText = 'Updated Risk Within Process successfully';
$scope.confirmationWin.open().center();
$scope.okCallback = $scope.riskAlignToProcessBack;
}
}
});
facotry.js
saveAllignRiskToProcess: function(processKey) {
return $http.post('app/risk/rest/riskTocontrol/saveCreateAndAlignNewRiskToProcess/' + processKey);
}
state.js
.state('createAndAlignRisk', {
url: '/risk/cnaRsk/:processKey',
templateUrl: 'views/risk/createNewRisk.html',
controller: 'RiskCtrl',
data: {
authenticate: true
}
})
consoleError
/riskTocontrol/saveCreateAndAlignNewRiskToProcess/[object%20Object]

If you want to pass both object $scope.riskDTO , $stateParams.processKey to service then the your service method needs to be change along with caller method code
Code
RiskService.saveAllignRiskToProcess($scope.riskDTO,$stateParams.processKey)
.then(function (response) {
//..code here
});
Service
saveAllignRiskToProcess: function(processKey, riskDTO) {
var url = 'app/risk/rest/riskTocontrol/saveCreateAndAlignNewRiskToProcess/' + processKey
return $http.post(url ,JSON.stringify({ 'serverSideParamName': riskDTO}) );
}

From angularjs doc
post(url, data, [config]);
data - Request content
The Data parameter is necessary that you can see from a documentation. You missed it in:
saveAllignRiskToProcess: function(processKey) {
return $http.post('app/risk/rest/riskTocontrol/saveCreateAndAlignNewRiskToProcess/' + processKey);
}

Related

How to do $state.go() with params?

I have perfectly initialized $stateProvider and I'm using all this states with ui-sref. Works great.
User presses the button and thorugh the $stateProvider goes to the edit page.
On this page I have a form which does $http request:
this.pushData = function (data) {
$http.post('/data/' + $stateParams.dataId + '/otherdata', JSON.stringify({
id: otherdata.id,
name: otherdata.name
}), configAuth).then(
function success(response) {
var addedData = response.data;
$.notify({message: addedData.name + " has been added"},{type:'success'});
$state.go('roleInfo({roleId: $stateParams.roleId})');
},
function error(data) {
console.log(data);
$.notify({message: data.data.message},{type:'danger'});
}
);
}
And I want to do redirect to other view if everything is fine. But this:
$state.go('roleInfo({roleId: $stateParams.roleId})');
doesn't work. How can I do $state.go with params?
The way you are trying that would work with ui-sref directive, while calling it using $state.go method, you should pass 1st parameter is stateName & then pass params in Object format.
$state.go('roleInfo', {roleId: $stateParams.roleId});
Try this:
$state.go('myStateName', {roleId: $stateParams.roleId});
You can read the docs here
i have changed
$state.go('roleInfo({roleId: $stateParams.roleId})'); to
$state.go('roleInfo',{roleId :$stateParams.roleId});
this will work
this.pushData = function (data) {
$http.post('/data/' + $stateParams.dataId + '/otherdata', JSON.stringify({
id: otherdata.id,
name: otherdata.name
}), configAuth).then(
function success(response) {
var addedData = response.data;
$.notify({message: addedData.name + " has been added"},{type:'success'});
$state.go('roleInfo',{roleId :$stateParams.roleId}); },
function error(data) {
console.log(data);
$.notify({message: data.data.message},{type:'danger'});
}
);
}

Angular $http.get not passing parameters

This seems like a simple problem, and I must be overlooking something small.
I have a function that accesses Spotify API and searches for an artist. I know that accessing this route via a normal URL returns a result. (e.g. http://localhost:3001/search?artist=%27Linkin%20Park%27) Here the code that does that:
router.get('/search', function(req, res, next)
{
var artist = req.param('artist');
console.log("Artist: " + artist);
smartSpot.getArtistID(artist, function(data)
{
console.log("Data: " + data);
res.json(data.id);
});
});
Then, there is the code on the front end to search for the artist. This is all done via angular.
angular.module('smart-spot', [])
.controller('MainCtrl', [
'$scope', '$http',
function($scope, $http)
{
$scope.createPlaylist = function()
{
var artist = $scope.artist;
console.log(artist);
window.open("/login", "Playlist Creation", 'WIDTH=400, HEIGHT=500');
return $http.get('/search?=' + $scope.artist) //this doesn't pass in the artist
.success(function(data)
{
console.log(data);
});
}
}
]);
The $http.get() does not pass in the $scope.artist` value properly.
Looks like you might be missing the "artist" query param in your string concatenation.
$http.get('/search?artist=' + $scope.artist)
Alternatively, you could pass the artist as a query param.
function createPlaylist() {
return $http.get('/search', { params : { artist : $scope.artist } })
.then(function(response) {
return response;
}, function(error) {
return $q.reject(error);
});
}
Also, I would avoid using .success. I believe that's depreciated in favor of the syntax above. First param is success function, second is fail function.
you can pass parameters via
$http.get('/search', {
params: {
artist: $scope.artist
}
})
.success(function(data)
{
console.log(data);
});

undefined is not a function using $resource [duplicate]

When trying to poll a custom method copies on an AngularJS Resource I get the following error at angular.js:10033: (The method copy works just fine.)
TypeError: undefined is not a function
at https://code.angularjs.org/1.3.0-beta.8/angular-resource.min.js:9:347
at Array.forEach (native)
at q (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:7:280)
at q.then.p.$resolved (https://code.angularjs.org/1.3.0-beta.8/angular-resource.min.js:9:329)
at J (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:101:5)
at J (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:101:5)
at https://code.angularjs.org/1.3.0-beta.8/angular.min.js:102:173
at g.$eval (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:113:138)
at g.$digest (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:110:215)
at g.$apply (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:113:468)
Angular.js 10016 - 10035:
function consoleLog(type) {
var console = $window.console || {},
logFn = console[type] || console.log || noop,
hasApply = false;
// Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
// The reason behind this is that console.log has type "object" in IE8...
try {
hasApply = !!logFn.apply;
} catch (e) {}
if (hasApply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args); // This is line 10033 where the error gets thrown.
};
}
Simplified resource:
angular.module('vgm.content-pages')
.factory('ContentPage', function($resource, $http) {
return $resource('/api/content-page/:id', { id:'#page.id' }, {
copy: {
method: 'POST',
url: '/api/content-page/copy/:id'
},
copies: {
method: 'GET',
isArray: true,
url: '/api/content-page/copies/:id'
}
});
});
Simplified directive where I'm getting the error:
angular.module('vgm.genericForms')
.directive('vgmFormCopyPicker', function() {
return {
restrict: 'E',
replace: true,
templateUrl: '/static/common/generic-forms/widgets/view-copy-picker.html',
scope: {
resource: '=',
},
controller: function($scope, $element) {
$scope.pages = [];
$scope.loadCopies = function() {
$scope.resource.$copies()
.then(function(response) {
$scope.pages = response.data;
});
};
}
};
});
As soon as I run the loadCopies method, executing the line $scope.resource.$copies() throws the error above.
In the Chrome Inspector I see the call to my API is actually being done. But resolving the promise seems to throw some error...
How can I solve this error?
EDIT:
$scope.resource = ContentPage.get({id: $stateParams.id}).$promise
$scope.resource.$save() // Works
$scope.resource.$update() // Works
$scope.resource.$copy() // Works
$scope.resource.$copies() // Does not work!
Angular Resource is trying to overwrite my initial resource with an array of items. But the instance of Resource does not have a method push of course.
I found the answer:
A resource is supposed to represent the matched data object for the rest of its lifespan. If you want to fetch new data you should do so with a new object.
$scope.copies = ContentPage.copies()
The answer from Guido is correct but I didn't get it at the first time.
If you add a custom method to your Angular $resource and using isArray: true and expecting to get an Array of something from your WebService you probably want to store the response in an Array.
Therefore you shouldn't use the instance method like this:
var ap = new Ansprechpartner();
$scope.nameDuplicates = ap.$searchByName(...);
But use the resource directly:
$scope.nameDuplicates = Ansprechpartner.searchByName(...)
Using following Angular resource:
mod.factory('Ansprechpartner', ['$resource',
function ($resource) {
return $resource('/api/Ansprechpartner/:id',
{ id: '#ID' },
{
"update": { method: "PUT" },
"searchByName": { method: "GET", url: "/api/Ansprechpartner/searchByName/:name", isArray: true }
}
);
}
]);
I am using Mean.js and this plagued for a few hours. There is a built in $update but it was not working when I tried to apply it to an object returned by a $resource. In order to make it work I had to change how I was calling the resource to update it.
For example, with a Student module, I was returning it with a $resource into $scope.student. When I tried to update student.$update was returning this error. By modifying the call to be Students.update() it fixed the problem.
$scope.update = function() {
var student = $scope.student;
var result = Students.update(student);
if(result){
$scope.message = 'Success';
} else {
$scope.error =
'Sorry, something went wrong.';
}
};

AngularJS: how should I set the params for $http dynamically?

I am very new with AngularJS. Thank you for answer. My code is as follow:
mainModule.controller('MainController', function($scope, $http) {
$http.get('http://localhost/backend/WebService.php', {params: {entity: 'IndexPageEntity'}}).
success(function(data) {
$scope.intro = data[0].IndexPageContent;
});
$http.get('http://localhost/backend/WebService.php', {params: {entity: 'ExhibitionServiceEntity'}}).
success(function(data) {
$scope.exhibit = data[0].ExhibitionServiceContent;
});
$http.get('http://localhost/backend/WebService.php', {params: {entity: 'ShootingServiceEntity'}}).
success(function(data) {
$scope.shooting = data[0].ShootingServiceContent;
});
});
My html file would be:
<div ng-controller="MainController">
<div>{{intro}}</div>
<div>{{exhibit}}</div>
<div>{{shooting}}</div>
</div>
I believe there must be some ways to improve the above code in order to reduce repetition. What I want is to pass entity parameter to the controller on creation.
Using ng-init to pass parameter is discouraged, according to the documentation. Writing custom directive to pass argument to scope does not work since parameters would be overwrittern.
What is the best practice to set params dynamically for use in $http? Thank you.
You should move all the logic to a service and use a directive. I would suggest you to modify your backend to return the same structured data, instead of IndexPageContent, ExhibitionServiceContent, etc. it should be Content or whatever name you want to use. But for now I've added a replace function to get the name of the content from the name of the entity.
mainModule.factory('webService', function($http) {
var apiUrl = 'http://localhost/backend/WebService.php';
function getContent(params) {
var config = {
'params': params
};
return $http.get(apiUrl, config);
};
return {
getContent: function(params) {
return getContent(params)
}
};
});
mainModule.controller('MainController', function($scope, webService) {
var params = {
'entity': $scope.entity
};
var contentName = $scope.entity.replace('Entity', 'Content');
webService.getContent(params).then(function (data) {
$scope.content = data[0][contentName];
});
});
mainModule.directive('EntityContent', function() {
return {
controller: 'MainController',
replace: true,
restrict: 'E',
scope: {
entity: '#entity'
},
template: '<div>{{ content }}</div>'
};
});
<div>
<entity-content entity="IndexPageEntity">
<entity-content entity="ExhibitionServiceEntity">
<entity-content entity="ShootingServiceEntity">
</div>
Create an object data and send the value for the key inside the object at every call.. Also pass the value for key to be set inside the scope..
E.g.
$scope.makeHttpCall = function(data) {
$http.get('http://localhost/backend/WebService.php', {params: data}).
success(function(data) {
$scope[$scope.key] = data[0][$scope.key];
});
};
you can then call this function as
$scope.key = 'IndexPageContent';
data = {
entity : 'yourValueHere'
};
$scope.makeHttpCall(data);
You can set other values as well inside the scope that are dynamic for each request..
I hope this makes sense to you...

TypeError: undefined is not a function in Angular Resource

When trying to poll a custom method copies on an AngularJS Resource I get the following error at angular.js:10033: (The method copy works just fine.)
TypeError: undefined is not a function
at https://code.angularjs.org/1.3.0-beta.8/angular-resource.min.js:9:347
at Array.forEach (native)
at q (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:7:280)
at q.then.p.$resolved (https://code.angularjs.org/1.3.0-beta.8/angular-resource.min.js:9:329)
at J (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:101:5)
at J (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:101:5)
at https://code.angularjs.org/1.3.0-beta.8/angular.min.js:102:173
at g.$eval (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:113:138)
at g.$digest (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:110:215)
at g.$apply (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:113:468)
Angular.js 10016 - 10035:
function consoleLog(type) {
var console = $window.console || {},
logFn = console[type] || console.log || noop,
hasApply = false;
// Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
// The reason behind this is that console.log has type "object" in IE8...
try {
hasApply = !!logFn.apply;
} catch (e) {}
if (hasApply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args); // This is line 10033 where the error gets thrown.
};
}
Simplified resource:
angular.module('vgm.content-pages')
.factory('ContentPage', function($resource, $http) {
return $resource('/api/content-page/:id', { id:'#page.id' }, {
copy: {
method: 'POST',
url: '/api/content-page/copy/:id'
},
copies: {
method: 'GET',
isArray: true,
url: '/api/content-page/copies/:id'
}
});
});
Simplified directive where I'm getting the error:
angular.module('vgm.genericForms')
.directive('vgmFormCopyPicker', function() {
return {
restrict: 'E',
replace: true,
templateUrl: '/static/common/generic-forms/widgets/view-copy-picker.html',
scope: {
resource: '=',
},
controller: function($scope, $element) {
$scope.pages = [];
$scope.loadCopies = function() {
$scope.resource.$copies()
.then(function(response) {
$scope.pages = response.data;
});
};
}
};
});
As soon as I run the loadCopies method, executing the line $scope.resource.$copies() throws the error above.
In the Chrome Inspector I see the call to my API is actually being done. But resolving the promise seems to throw some error...
How can I solve this error?
EDIT:
$scope.resource = ContentPage.get({id: $stateParams.id}).$promise
$scope.resource.$save() // Works
$scope.resource.$update() // Works
$scope.resource.$copy() // Works
$scope.resource.$copies() // Does not work!
Angular Resource is trying to overwrite my initial resource with an array of items. But the instance of Resource does not have a method push of course.
I found the answer:
A resource is supposed to represent the matched data object for the rest of its lifespan. If you want to fetch new data you should do so with a new object.
$scope.copies = ContentPage.copies()
The answer from Guido is correct but I didn't get it at the first time.
If you add a custom method to your Angular $resource and using isArray: true and expecting to get an Array of something from your WebService you probably want to store the response in an Array.
Therefore you shouldn't use the instance method like this:
var ap = new Ansprechpartner();
$scope.nameDuplicates = ap.$searchByName(...);
But use the resource directly:
$scope.nameDuplicates = Ansprechpartner.searchByName(...)
Using following Angular resource:
mod.factory('Ansprechpartner', ['$resource',
function ($resource) {
return $resource('/api/Ansprechpartner/:id',
{ id: '#ID' },
{
"update": { method: "PUT" },
"searchByName": { method: "GET", url: "/api/Ansprechpartner/searchByName/:name", isArray: true }
}
);
}
]);
I am using Mean.js and this plagued for a few hours. There is a built in $update but it was not working when I tried to apply it to an object returned by a $resource. In order to make it work I had to change how I was calling the resource to update it.
For example, with a Student module, I was returning it with a $resource into $scope.student. When I tried to update student.$update was returning this error. By modifying the call to be Students.update() it fixed the problem.
$scope.update = function() {
var student = $scope.student;
var result = Students.update(student);
if(result){
$scope.message = 'Success';
} else {
$scope.error =
'Sorry, something went wrong.';
}
};

Categories