How to display json from server after success? - javascript

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);

Related

returning image/jpeg as arraybuffer or blob

I am currently making a call to my api which returns an image as an image/jpeg. My issue is the when calling the url through javascript angular .factory resource I am getting my array buffer as empty {}. Also, the bytes length is 0. If I make the call to the api url with response type '' or 'text' I do see value of multiple types. What am I missing here? Thank you for your help!
JS:
.factory("Img", function($resource) {
return $resource("http://mypathTo/image/:id", {
id: "#id"
}, {
responseType: '' //arraybuffer return empty
});
});
app.controller //code
$scope.getImage = function(productid) {
console.log(productid);
par = {id: [productid]};
Img.getImage(par).$promise.then(
function(data){
console.log("success:" + data); //I am able to see bytes when coming back as text but not with arraybuffer as data.bytelength = 0
scope.productionPicturePath = data;
return data;
},
function(data){
console.log("error" + data);
}
);
}
}
The $resource service can only return JavaScript objects or arrays depending on isArray. To get exotic objects such as ArrayBuffer or Blob, use the $http service.
The DEMO
angular.module("app",[])
.controller("ctrl", function($scope,$http) {
var vm = $scope;
var url="//i.imgur.com/fHyEMsl.jpg";
var config = { responseType: 'blob' };
$http.get(url,config)
.then(function(response) {
console.log("OK");
//console.log(response.data);
vm.blob = response.data;
vm.dataURL = URL.createObjectURL(vm.blob);
console.log(vm.dataURL);
}).catch(function(response) {
console.log("ERROR");
throw response;
});
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
BLOB type {{blob.type}}<br>
BLOB size {{blob.size}}<br>
<img ng-src="{{dataURL}}" height="100" />
</body>

Output of Restangular data

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

How to iterate over an array stored in an object using ng-repeat

I make a call to an API endpoint which returns a single object. I want to loop over an array named video stored in the object and return all the links stored in the array to the view.
JSON object returned from the API
html code
<div class="myVideo" ng-repeat="v in courses.video">
<iframe width="560" height="315" ng-src="{{'v.video'}}"
frameborder="10" allowfullscreen></iframe>
</div>
Function in controller for API call
$scope.getCourse = function(id){
coursesFac.getCourseById(id)
.then(function (response) {
$scope.courses = response.data;
var items =response.data;
console.log(items);
//console.log($scope.courses.video);
}, function (error) {
$scope.status = 'Unable to load course data: ' + error.message;
console.log($scope.status);
});
};
This error appears on the view where videos should be displaying
courses.video is a string - not an array. You need to parse the json
$scope.getCourse = function(id) {
coursesFac.getCourseById(id)
.then(function(response) {
response.data.video = JSON.parse(response.data.video); //HERE
$scope.courses = response.data;
var items = response.data;
console.log(items);
//console.log($scope.courses.video);
}, function(error) {
$scope.status = 'Unable to load course data: ' + error.message;
console.log($scope.status);
});
};

Angular File upload formData

I'm using Angular-File-Upload, the problem that is I can't send a formData along with the file. Following is my code:
$scope.addProducts = function(){
console.log($scope.product);
ProductApi.addProduct($scope.product)
.then(function(response){
ngNotify.set('Your product has been added!', {
position: 'bottom',
duration: 2000
});
$scope.product_id = response.data;
uploaderImages.uploadAll();
})
.catch(function(response){
console.log(response.data);
})
}
What the above code does is, once the form is submit, the form will is send via api call. The response will be an product_id and uploaderImages.uploadAll(); is triggered!!(This stuff work perfectly). Following is uploaderImages that will post file to server:
var uploaderImages = $scope.uploaderImages = new FileUploader({
url: '/api/productimg',
onBeforeUploadItem: function(prod){
var ids = $scope.product_id
var prodid = { proid: $scope.product_id} ---> empty
prod.formData.push(prodid)
console.log($scope.product_id) ----> product_id = 32
},
onCompleteAll: function(){
console.log($scope.product_id); ----> product_id = 32
},
onSuccessItem: function(prodId,response,status,headers){
}
});
I had no idea how to tackle this prob, proid:product_id return as [object Object], if I assign proid as a fixed integer ie proid:23, it works.
PLEASE HELP!!!!!
You need to access the value of the product_id not just the response payload:
$scope.product_id = response.data.product_id;
Also, because you are using Promises you need to chain your methods. Try:
$scope.addProducts = function(){
console.log($scope.product);
ProductApi.addProduct($scope.product)
.then(function(response) {
return ngNotify.set('Your product has been added!', {
position: 'bottom',
duration: 2000
}, function(error) {
console.log(error);
}) // assuming this is async so add another then block below to execute once this is done
.then(function(response) {
$scope.product_id = response.data.product_id; // response.data will give you the whole response payload if the object returned is {product_id: 123}
uploaderImages.uploadAll();
});
}
Note that the error handler is a callback to the first .then block (see the docs).

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