Getting Json data from http module


#1

Hi,
Today im trying to get some data from API.
But i don’'t know how to transform result of http request as json. I’m getting this instead: [object Promise]

My code is as follows, and my issue is below // This console will return [object Promise] comment.

Thanks for advice.

var Observable = require(“data/observable”).Observable;
var pageData = new Observable();

function loaded(args) {
var page = args.object;
// Get navigation context
var gotData=page.navigationContext;

var http = require("http");
var x;


var a = http.getJSON("https://jsonplaceholder.typicode.com/posts/1").then(function (r) {
    //console.log(a);
}, function (e) {
    //console.log(e)
});

// This console will return [object Promise]
console.log(a);

// Create new observable object model
var model = new Observable();

// get id from prevoius frame context, convert to number first
var selectedId = Number.parseInt(gotData.id);

// Just assign id to observable
model.id = selectedId;

// Dummy array of projects
var project = [
  { id:11,  name:'Arcade Filter',  desc: "Build a Rocket Boys!",   image:'~/images/show/1.jpg'},
  { id:12,  name:'Arcade Filter2', desc: "Build a Rocket Boys!",   image:'~/images/show/1.jpg'},
  { id:13,  name:'Arcade Filter3', desc: "Build a Rocket Boys!",   image:'~/images/show/1.jpg'},
];

// Project with found id, now search for this id and get all infos
var item = project.find(item => item.id === selectedId);

// Bind rest of details.
model.name  = item.name;
model.desc  = x;
model.image = item.image;

// Bind model object
page.bindingContext = model;

};

// export data
exports.loaded = loaded;


#2

r points to JSON here.

http.getJSON("https://jsonplaceholder.typicode.com/posts/1").then(function (r) {
    //console.log(r);
}, function (e) {
    //console.log(e)
});

#3

Thank you @manojdcoder for express answer !

Now this works, i have only one issue now, as result of my code will return [object Promise] instead of id here. Is there any workaround ?
Thanks.

var http = require("http");
var x;

var a = http.getJSON("https://jsonplaceholder.typicode.com/posts/1").then(function (r) {
    x = JSON.stringify(r.id);
    return x;
}, function (e) {
    //console.log(e)
});

// This console will return [object Promise]
console.log(a);

#4

im not sure if its the same for vanilla but in angular, you need to use .map() not .then()


#5

@Konrad
When you return x from the function inside then block. It does not get assigned to your variable a

you should instead do

http.getJSON("https://jsonplaceholder.typicode.com/posts/1").then(function (r) {
    a = JSON.stringify(r.id);
    console.log("A is: ", a);
}, function (e) {
    //console.log(e)
});

and you can use the value of a only inside that block.

Because it is asynchronous.


#6

Thank you @multishiv19 but what im getting outside of http is:

A is: undefined

var a;
http.getJSON("https://jsonplaceholder.typicode.com/posts/1").then(function (r) {
    a = JSON.stringify(r.id);
}, function (e) {
    //console.log(e)
});
console.log("A is: ", a);

#7

thats because it logs what a is before it has data. move the log to inside the function or in a set timeout of 5-10 seconds


#8

Thank you. Im supprised, that we have no simple way of returnig value from http ? very strange for me.
It seems taht timeout may work here, but as you know - 5 secs delay will riun UI in many situation.

I think i will test this:


#9

ive never used vanilla so im not sure entirely, but in angular its easy. as for the delay, 5 seconds is very little time to wait, you shouldnt need the plugin


#10

Thank you.
My concern is - right now im learning but i have creating app in future in my plans. App will relly on external API in ery many places, so i cant imagine that i can use delay so many times…


#11

@Konrad
No one accesses async data in sync code.

HTTP response is always async. You should access its response only inside the then block.

Not sure what you are trying to do there.


#12

What im trying to do ?
All i want is to connect with external API using http, get data from the server, and to have ability to bind this data foe later use.
So i want to grab user name, id image, bind this into view and show …


#13

i do similar in my app, i wait for the data to return which takes all of a couple of seconds max, its not slow at all


#14

Thanks for reply.
I’m front end coder, so things are unfamiliar for me. I expacted that http will work in similar way to Jquery ajax for example. This is why i’m confused :slight_smile:


#15

i never used jquery, ive always been against it. unless your data is taking over 10 seconds to return, it should be fine for the user


#16

Hi @Konrad you have two options, core options without plugins.

Example:

const Observable = require("tns-core-modules/data/observable").Observable;

var viewModel = new Observable({  
    myData: new ObservableArray.ObservableArray([])
});

var a;
http.getJSON("https://jsonplaceholder.typicode.com/posts/1").then(function (response) {
    a = JSON.stringify(response.id);
    viewModel.set("myData", a); 

}, function (e) {
    //console.log(e)
});
//console.log("A is: ", a);

You can also set viewModel.set("myData", response); as response is Object in this case and you can access it’s data anywhere in the View. And it is Observable as well.
If you need more “permanent” solution for each session, then use application storage with good example here: https://www.nativescript.org/blog/using-device-local-settings-with-nativescript