Output of Restangular data - javascript

Hello I have output data from my API
I use Restangular libary
My service
order.getclient=function(order){
return Restangular
.all('/clients/'+order.client.id).customGETLIST(null, null);
};
My controller
$scope.fetchGetClient=function(){
$scope.client = Order.getclient($scope.order).$object;
};
out in html
<div ng-init="fetchGetClient()">
{{client}}
</div>
I get empty array
I also tried
$scope.fetchGetClient=function(){
Order.getclient($scope.order).then(function (response) {
$scope.client = response
console.log(response)
});
console.log also empty
thanks

Related

Return request response in angularJs

I've setup a controller and service to grab some JSON from my own NodeJS API/MongoDB endpoint.
In my browser console I see a returned object and 5 items and when I query my api I see the same json in the browser, so I know it's working on the server side.
I'm confused though about why when attempting to NG-Repeat through this I get nothing on page and when I console log out the returned data, it comes back undefined.
I'm new to the HTTP module and I'm trying to refactor out DB calls to a service instead of using it in controller.
--- Controller code ---
vm.getDepartments = function() {
vm.departments = DbService.getAllDepartments();
console.log(vm.departments);
}();
--- Service Code (using $http) ---
function getAllDepartments() {
$http.get('/api/departments').then(function(err, response) {
if (err) {
console.log(err);
}
return response;
});
};
--- html page ---
<tbody>
<tr ng-repeat='dept in vm.departments'>
<td>{{ dept.departmentLong }}</td>
<td>{{ dept.departmentShort }}</td>
<td>
<button class='btn btn-warning'><span class='glyphicon glyphicon-edit'></span></button>
<button class='btn btn-danger' ng-click='vm.deleteDepartment(dept);'><span class='glyphicon glyphicon-ban-circle'></span></button>
</td>
</tr>
</tbody>
You used wrong then method.
The then() method takes two arguments: a success and an error callback which will be called with a response object.
Using the then() method, attach a callback function to the returned promise.
Have a look to an old answer posted by mine.
$http.get('/api/departments') returns a promise, so you can create a function which returns only the promise, as #sachila ranawaka mentioned.
function getAllDepartments() {
return $http.get('/api/departments')
};
In the controller use then method which I mentioned above.
DbService.getAllDepartments().then(function(response) {
vm.departments = response.data;
console.log(vm.departments);
},function(error){
console.log(err);
});
Another method is to create a callback function, and pass it to getAllDepartments method.
function getAllDepartments(callback) {
$http.get('/api/departments').then(function(response) {
callback(response);
});
};
Controller code:
vm.getDepartments = function() {
vm.departments = DbService.getAllDepartments(function(result){
console.log(result);
});
}();
in the service just return the http request
function getAllDepartments() {
return $http.get('/api/departments')
};
And catch the promise inside the controller. use response.data to get the data
vm.getDepartments = function() {
DbService.getAllDepartments().then(function(response) {
vm.departments = response.data;
console.log(vm.departments);
});
}

ngResource + 401 error handling: Expected response either an array or an object

I am using the following code with ngResource to retrieve a list of objects:
// Create the 'articles' service
angular.module('articles').factory('Articles', ['$resource', function($resource) {
// Use the '$resource' service to return an article '$resource' object
return $resource('../api/admins/:adminId/articles/:articleId', {
adminId: '#adminId'
}, {
update: {
method: 'PUT'
}
});
}]);
Articles are retrieved like so:
$scope.list = function() {
// Use the articles'query' method to send an appropriate GET request
Articles.query(
function(articles){
$scope.data.articles= articles;
},
function(error){
console.log(error);
}
);
};
When a user is logged in, all works fine: The client expects an array and that's what it gets.
But after a while when the login timed out, the server will return a 401 error with an object instead of an array. In fact, this is EXACTLY what is supposed to happen, but Angular throws the following error:
Error: [$resource:badcfg] Error in resource configuration.
Expected response to contain an array but got an object
The same problem occurs when a user retrieves a page that is forbidden (403).
Is there a way to resolve 401 and 403 request errors without getting an actual javascript error in Angular?
the query action of $resource by default expects an array to be returned from the server (see the docs).
You could use the transformResponse option for the query action to compensate for this like so:
return $resource('../api/admins/:adminId/articles/:articleId', {
adminId: '#adminId'
}, {
update: {
method: 'PUT'
},
query: {
transformResponse: function(data, headers) {
if(!angular.isArray(data)) {
return new Array(data);
}
return data;
}
}
});
Of course it would be much better to handle errors using the error callback or with an interceptor

How to display json from server after success?

I am creating a login controller on Angular and I have a factory service in which I send a post request and return json data. When I console.log the success data I can see an object however when i try to access the properties I am getting undefined.
UserAuthFactory.login(name,password)
.success(function(data){
console.log(data.token);
AuthenticationFactory.token = data.token;
console.log(data);
}).error(function(status){
console.log('oops something went wrong.');
});
};
in my console.log
Object {success: true, message: "Enjoy Your Token!", token:
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJfaWQiOiI1N…jowfQ.Hcfejg7x7W4w01fBaf303I2iJ57T38e84vLtGDiwSHI"}
message: "Enjoy Your Token!"success: truetoken:
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJfaWQiOiI1NjUzODEyNjg2NzFhM2JhMmQ2NTQ4NjgiLCJuYW1lIjoiTmljayBHbG9uYXJpcyIsInBhc3N3b3JkIjoicGFzc3dvcmQiLCJhZG1pbiI6dHJ1ZSwiX192IjowfQ.Hcfejg7x7W4w01fBaf303I2iJ57T38e84vLtGDiwSHI"proto:
Object app.js:121 undefined
How can I then access the different properties of the array? Properties such as token, message, etc?
If you want to access that data in HTML part, refer to my example code.
I did use $scope, $http module.
example.controller('Example', function( $scope, $http ) {
$scope.token = '';
$scope.message = '';
$scope.etc = null;
$scope.getToken = function() {
var reqParams = { id: 'userid', password: 'owije3wefo' };
$http.post('getToken', reqParams ).then( function( res ) {
console.log( res.data );
this.result = res.data.token;
this.message = res.data.message;
this.etc = res.data.etc;
}.bind(this));
};
});
In html,
<div ng-controller="Example">
<div>
<span class="label">token</span>
<input ng-model="token" type="text" />
</div>
</div>
When you have a JSON object you should only convert it with the function
JSON.parse(text)
For example
var json_object = JSON.parse(json_string);
console.log(json_object.parameter);

Angularjs not loading json files

I'm not sure why when i print the json file on a html page works, also from a button calling a function, but not inside of the javascript file.
This a problem because i need to sort the data in the json file before displaying it from in the web page, i can't make it work. i tried using this solution https://stackoverflow.com/a/15463124/2796268,
but the console say
jsonDat is not defined
my code:
$scope.init = function () {
console.log("init");
$http.get('json/file.json') .success(function(data) {
$scope.jsonDat = res.data;
})
.error(function(data,status,error,config){
$scope.jsonDat = [{heading:"Error",description:"Could not load json data"}];
});
console.log(jsonDat);
};
How i can process the json data before the page loads or when the page is loading?
You can process the data when it is returned from $http, like so:
$scope.init = function () {
$http.get('json/file.json').success(function(data) {
//---- SORT HERE ----
$scope.jsonDat = mySortFunction(data);
});
};
Try this :
$scope.init = function() {
console.log("init");
$http.get('json/file.json').success(function(data) {
$scope.jsonDat = data;
console.log($scope.jsonDat);
})
.error(function(data, status, error, config) {
$scope.jsonDat = [{
heading: "Error",
description: "Could not load json data"
}];
console.log($scope.jsonDat);
});
};
In success you have data but you try get from res.data. When you use success then it is not response with data but only your data.
I thought you wanna sort some JSON file then display it in HTML page . So My Idea is get that JSON file (you tried)
$http.get('json/file.json') .success(function(data) {
$scope.jsonDat = data.res;
console.log('Checking the result',angular.toJson($scope.jsonDat));
})
But putting your result in
$scope.jsonDat = data.res;
eg,
sortService.sortJsn = data.res;
$scope.jsonDat instead create angular service pour your data there then you can access those data any where in your controller sort it also show it in HTML.

How to get a variable from the Angular controller to a view

I have a controller that looks like this:
angular.module('my_app')
.controller('QueryCtrl', ['$scope', 'Query', function ($scope, Query) {
$scope.onSubmit = function() {
var json = $.post('http://162.243.232.223:3000/api/query', { 'input': 'my_input' });
console.log(json);
$scope.queries = json;
};
}
])
And a view that looks like this:
<div ng-controller="QueryCtrl">
<form ng-submit="onSubmit()" >
<textarea ng-model="query_box" name="my_input"></textarea>
<button type="submit">Submit</button>
</form>
{{ queries }}
<ul ng-repeat="query in queries">
<li>{{query}}</li>
</ul>
</div>
The problem is that, when I click the submit button, the javascript console successfully logs the correct json object, which has a property
responseJSON
You can take a closer look at the object I want by looking typing
$.post('http://162.243.232.223:3000/api/query', { 'input': 'my_input' });
into the javascript console yourself and checking out the object.
However, in the view, when I print out the "queries" object, it appears to not have a responseJSON attribute, but only a readyState attribute.
Where is the rest of my json object?
Try something like this:
$scope.onSubmit = function() {
var json = $.post('http://162.243.232.223:3000/api/query', { 'input': 'my_input' });
json.done(function(result){
$scope.result = result;
$scope.$apply();
})
console.log(json);
$scope.queries = json;
};
}
<div>{{result}}</div>
var projectangular.module('my_app')
.controller('QueryCtrl', ['$scope', 'Query', function ($scope,$http, Query) {
$scope.onSubmit = function() {
$http.post('http://162.243.232.223:3000/api/query', { 'input': 'my_input' }).then(
//sucess
function(response){
angular.copy(response ,$scope.queries);
console.log(json);
},
//error
function(){
alert("cant post");
});
};
}
])
As CAT commented, what you got back from .post is a promise object. You will have to wait for post request to complete (fail or succeed). Following syntax may be little off. I just typed it on the fly.
angular.module('my_app').controller('QueryCtrl', ['$scope', 'Query', function ($scope, Query) {
$scope.onSubmit = function() {
var json = $.post('http://162.243.232.223:3000/api/query', { 'input': 'my_input' }).then(function(response){
console.log(response.data);
$scope.queries = response.data;
$scope.$apply();
}, function(response){
console.log(response.data);
$scope.queries = response.data;
$scope.$apply();
});
};
}])
That's because of the promise system and how the objects are printed in the console, they are printed by reference and not by value. Try doing console.log(JSON.stringify(json)) which is a string and not an object and you will see that you are missing the the responseJSON attribute. you responseJSON attribute is probably attached to the object at a future time but the console.log(Object) will print it's current value, even tho that value was added after you used console.log.

Categories

Resources