Nativescript pass fetch response data to a level text - android

In my nativescript app,I am trying to bulid a level from the response of my API through fetch module.But I don't know how to bind the context in obserable.How to bind the context when page loaded.Here is my code-
Response from my api-
[{"value":"12000$"}]
I want to get that value from response in {{price}} in my level text.
view file-
<Page loaded="loaded">
<GridLayout>
<Label text="{{ price }}" horizontalAlignment="left" verticalAlignment="center" tap="model" />
</GridLayout>
</Page>
Fetch request-
fetch("http://10.0.2.2:8000/get_model", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
brand: data,
})
}).then(r => { return r.json(); }).then(function (data) {
console.log(data[0].value);
//How to push the value in obserable?
}, function (e) {
console.log("Error occurred " + e);
});

var observableModule = require("data/observable");
var viewModel = new observableModule.Observable();
viewModel.set("ip", "none"); // initial value
function onLoaded(args) {
var page = args.object;
page.bindingContext = viewModel;
fetch("http://httpbin.org/ip", {
method: "GET",
headers: { "Content-Type": "application/json" }
})
.then(function (res) { return res.json(); })
.then(function (data) {
console.log(data.origin); // make sure you are getting the value
viewModel.set("ip", data.origin); // binding to "price"
})
}
exports.onLoaded = onLoaded;
and in your page.xml use the loaded event
<Page loaded="onLoaded">
<Label text="{{ ip }}"/>
</page>
In this case, httpbin.org is returning the data in format
{"origin" : "some-ip-address-here"}

Related

How to use ImageCache Nativescript core module

I'm trying to save and load images from cache using ImageCache NativeScript Core module but it won't work.
<template>
<Page>
<StackLayout>
<Image v-for="exampleImage in exampleImages" :src="getCachedImage(exampleImage.url)"/>
</StackLayout>
</Page>
</template>
<script>
import * as imageCache from 'tns-core-modules/ui/image-cache'
import * as imageSource from 'tns-core-modules/image-source'
export defualt {
data() {
return {
exampleImages: [
{url: 'https://image.tmdb.org/t/p/w600_and_h900_bestv2/kY2c7wKgOfQjvbqe7yVzLTYkxJO.jpg'},
{url: 'https://image.tmdb.org/t/p/w600_and_h900_bestv2/svIDTNUoajS8dLEo7EosxvyAsgJ.jpg'},
{url: 'https://image.tmdb.org/t/p/w600_and_h900_bestv2/A7XkpLfNH0El2yyDLc4b0KLAKvE.jpg'},
]
}
},
methods: {
getCachedImage(imgUrl) {
const cache = new imageCache.Cache();
cache.enableDownload();
const image = cache.get(imgUrl);
let cachedImageSource;
if (image) {
console.log('getting image from cache')
cachedImageSource = imageSource.fromNativeSource(image)
} else {
console.log('downloading image, setting it in cache, and getting from cache')
cache.push({
key: imgUrl,
url: imgUrl,
completed: (image, key) => {
if (imgUrl === key) {
cachedImageSource = imageSource.fromNativeSource(image);
console.log(cachedImageSource)
}
},
error: () => {
console.log('Error')
}
});
}
cache.disableDownload();
return cachedImageSource;
}
}
}
</script>
But then, the output in my console is the following:
iOS:
{ ios: {} }
Android:
{ android:
{ constructor:
{ [Function]
[length]: 0,
[name]: '',
[arguments]: null,
[caller]: null,
[prototype]: [Object],
createBitmap: [Object],
createScaledBitmap: [Object],
extend: [Object],
CREATOR: [Object],
DENSITY_NONE: 0,
CONTENTS_FILE_DESCRIPTOR: 1,
PARCELABLE_WRITE_RETURN_VALUE: 1,
null: [Circular],
class: [Object],
CompressFormat: [Object],
Config: [Object] } } }
And of course is always outputing: downloading image, setting it in cache, and getting from cache and never getting image from cache. The image is never displayed, never saved in cache and never obtained from cache.
I don't know what I'm I doing wrong.
Thanks in advance.
Image download is asynchronously, so you can not use a direct return statement. You have to wait for the complete callback and update your data with image url.
<template>
<Page class="page">
<ActionBar title="Home" class="action-bar" />
<ScrollView>
<StackLayout>
<Image v-for="exampleImage in exampleImages" :src="exampleImage.src" />
</StackLayout>
</ScrollView>
</Page>
</template>
<script>
import * as imageCache from "tns-core-modules/ui/image-cache";
import * as imageSource from "tns-core-modules/image-source";
export default {
data() {
return {
exampleImages: [{
url: "https://image.tmdb.org/t/p/w600_and_h900_bestv2/kY2c7wKgOfQjvbqe7yVzLTYkxJO.jpg",
src: null
},
{
url: "https://image.tmdb.org/t/p/w600_and_h900_bestv2/svIDTNUoajS8dLEo7EosxvyAsgJ.jpg",
src: null
},
{
url: "https://image.tmdb.org/t/p/w600_and_h900_bestv2/A7XkpLfNH0El2yyDLc4b0KLAKvE.jpg",
src: null
}
]
};
},
methods: {
getCachedImage(exampleImage) {
const cache = new imageCache.Cache();
cache.enableDownload();
const image = cache.get(exampleImage.url);
let cachedImageSource;
if (image) {
console.log("getting image from cache");
exampleImage.src = imageSource.fromNativeSource(image);
} else {
console.log(
"downloading image, setting it in cache, and getting from cache"
);
cache.push({
key: exampleImage.url,
url: exampleImage.url,
completed: (image, key) => {
exampleImage.src = imageSource.fromNativeSource(
image);
},
error: () => {
console.log("Error");
}
});
}
// cache.disableDownload();
}
},
created() {
for (let x in this.exampleImages) {
this.getCachedImage(this.exampleImages[x]);
}
}
};
</script>
Updated Playground

React-Native multipart photo upload not working in android

I'm trying to send/upload image file to my back-end serve using fetch multipart upload in react-native, but fetch multipart form data upload is not working for android, however I tried different examples.
Image upload multipart form data API is based on php and its working for iOS react-native app.
I am using react-native-photo-upload library for taking image.
storePicture(PicturePath:string) {
console.warn(PicturePath);
if (PicturePath) {
const apiUrl = `${Constants.APIHOST}updateprofileimage.php`;
// Create the form data object
var data = new FormData();
data.append('profileimage', { uri:PicturePath, name: 'profileimage.jpg', type: 'image/jpg/jpeg' });
data.append('accesstoken', this.state.user.sAccessToken);
data.append('react-native', 1);
// Create the config object for the POST // You typically have an OAuth2 token that you use for authentication
const config = { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'multipart/form-data;' }, body: data };
fetch(apiUrl, config)
.then(responseData => { // Log the response form the server
// Here we get what we sent to Postman back
console.warn(`response:${responseData}`);
})
.catch(err => {
console.warn(err);
});
}}
Here is the example how I am calling storePicture() function.
<PhotoUpload onResizedImageUri={
avatar => {
if (avatar) {
this.storePicture(avatar.path);
}
}}
>
<Image source={{uri: this.state.user.sProfileImageUrl}} style={{resizeMode:"cover", marginTop:8.0, backgroundColor:'transparent', height:120.0, width:120, borderRadius:60.0, borderWidth:0.0, borderColor:'transparent'}}/>
</PhotoUpload>
uploadProfileImage = async (image:var) => {
this.setState({
loading: true
});
var RNFS = require('react-native-fs');
const path = Style.IS_IOS ? image.uri : image.path;
var fileName = path.split('/').pop();
var fileType = fileName.split('.').pop();
var filePath = Style.IS_IOS ? path : 'file://' + path;
const apiURL = `${Constants.APIHOST}updateprofileimage.php`;
const formData = new FormData();
formData.append('accesstoken', this.state.user.sAccessToken);
formData.append('reactnative', 1);
formData.append('profileimage', {
uri:filePath,
name: fileName,
type: `image/${fileType}`,
});
try {
const response = await fetch(apiURL, {
body: formData,
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json',
},
})
const json = await response.json()
this.handleUploadImageResponse(json);
} catch (err) {
this.setState({
loading: false
},console.log('catch Error: '+ err));
}
}
I am answering my own question as I haven't found any valid answer for the sake of other users, who are facing same issue.
Please let me know if I can improve my answer/post or in case any help is needed from me.
Image Upload to an API by Multipart FormData
uploadPicture = () => {
console.log(
"Image Upload urI = " + JSON.stringify(this.state.imageSourceUri.uri)
);
this.setState({ loading: true });
const form = new FormData();
form.append("fileToUpload", {
uri: this.state.imageSourceUri.uri,
type: "image/jpg",
name: "12334"
});
fetch("http://119.82.97.221/HPBSProjectApi2/api/HPBS/PostFormData", {
method: "post",
body: form
})
.then(response => response.json())
.then(response => {
console.log("response = " + response);
this.setState({
loading: false
});
});
};
the problem is the type field in the FormData, use mime to resolve it. Images must be image/jpeg.
const formData = new FormData();
formData.append("image",{..., name, uri, type: mime.getType(uri)}));

Value for title can not be cast from ReadablenativeMap to string

Consider:
InsertDataToServer = () => {
const { pinValue1 } = this.state;
const { pinValue2 } = this.state;
const { pinValue3 } = this.state;
const { pinValue4 } = this.state;
var String_3 = pinValue1.concat(" ", pinValue2);
var String_4 = String_3.concat(" " , pinValue3);
var String_5 = String_4.concat(" " , pinValue4);
fetch("http://www.aonde.biz/mobile/doLogin.php", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
"pin": 212,
})
})
.then(response => response.json())
.then(responseJson => {
// Showing the response message coming from
// the server after inserting records.
Alert.alert(responseJson);
})
.catch(error => {
console.error(error);
});
In the above code, when I pass the "pin" parameter API, it shows this error:
How can I resolve this issue?
This error was fixed when the code changed from:
Alert.alert('Error:', error)
to:
Alert.alert('Error:', error.message)
In your Alert.alert(responseJson);, you need to stringify it like this:
Alert.alert(JSON.stringify(responseJson));
Keep in mind that alert is a component from the mobile app, so it might not understand the code shown there is JSON content. If that doesn't work, use responseJson.text().
Make sure your alerts are displaying the error.MESSAGE and not the whole error. Depending on the error and its type that might be the cause!
That was the cause of my issue.
The error was fixed when adding the title in the Alert method.
As in the documentation, the title of Alert must be given while calling the Alert method.
I have had a similar issue. I solved it by changing one of the syntax. In your case, try this:
fetch("http://www.aonde.biz/mobile/doLogin.php",
method: "POST",
header: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
"pin":212,
})
)
What I changed to your coding: I removed {} after the URL.
If you get a red line error on the :, then remove method: header: and body: as well. The code will be like this:
fetch("http://www.aonde.biz/mobile/doLogin.php",
"POST",
{
Accept: "application/json",
"Content-Type": "application/json"
},
JSON.stringify({
"pin":212,
})
)
You can check if its string before sending it to Alert.alert method:
const title = "Error title..";
const errorMessage = (typeof error === 'string' || error instanceof String) ? error : error.message;
Alert.alert(title, errorMessage);
I was having this error because I installed a library that needed me to compile the app again and I hadn't compiled it.
After compiling again everything worked fine.
You can simply remove double quotation marks from pin.
fetch("http://www.aonde.biz/mobile/doLogin.php", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
pin:212,
})
})

In Nativescript the result from imageSource.fromUrl is coming as {"android":{}}

While following the link https://docs.nativescript.org/cookbook/image-source, in the console, am getting the result as {"android":{}} in my android device.
Below is my js code
var createViewModel = require("./main-view-model").createViewModel;
var imageSource = require("image-source");
function onNavigatingTo(args) {
var page = args.object;
imageSource.fromUrl("https://www.google.com/images/errors/logo_sm_2.png")
.then(function (res) {
console.log("Image successfully loaded");
console.log(JSON.stringify(res));
}, function (error) {
//console.log("Error loading image: " + error);
});
page.bindingContext = createViewModel();
}
exports.onNavigatingTo = onNavigatingTo;
Should we do anything more to get the image. Apologies if the question is too basic, just getting to know Nativescript
There are several approaches to load an image from URL - you can create an instance of image via code behind and attach the imageSource to its src and then dynamically added the image to a page container element (e.g. grid-layout, stack-layout or else)
Or, you can use data binding and once you get the imaageSource to bind it with your view model.
example given:
page.js
var observable_1 = require('data/observable');
var imageSource = require("image-source");
function navigatingTo(args) {
var page = args.object;
var viewModel = new observable_1.Observable();
imageSource.fromUrl("https://www.google.com/images/errors/logo_sm_2.png")
.then(function (res) {
viewModel.set("myUrl", res);
}, function (error) {
//console.log("Error loading image: " + error);
});
page.bindingContext = viewModel;
}
exports.navigatingTo = navigatingTo;
page.xml
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo">
<StackLayout>
<Label text="ImageSource fromUrl example" class="title"/>
<Image src="{{ myUrl }}" stretch="none" />
</StackLayout>
</Page>

AJAX call not getting information on Intel XDK

I'm building an APK for the blood bank of my local city and i need to get the stock of blood by groups, i have some JSON that i test with Postman that woks but i need to add them to my Intel XDK project. I have follow some examples with AJAX and HTTP but with no result.
ionic.Platform.ready(function(){
$("#ajax").click(function(){
$.ajax({
method: 'GET',
url: 'http://192.168.1.100/api/hospital/17659861-1',
dataType: 'json',
success: function (data) {
alert('Data RecibidaAPI: ' + data);
console.log(data.data[0].us_rut);
console.log(data.data[0].us_nombre);
console.log(data.data[0].us_telefono);
console.log(data.data[0].us_id_dispositivo);
console.log(data.data[0].us_grupo_sangre);
}
}).then(function (data) {
console.log('Data RecibidaAPI: ' + data);
});
});
}
and also try
<div id="campa_de_sangre" class="upage-content vertical-col left hidden" ng-app="myApp2" ng-controller="myCtrl2">
<p>hola</p>
<h1>{{myWelcome}}</h1>
<p>Status : {{statuscode}}</p>
<p>StatusText : {{statustext}}</p
<p>{{content}}</p>
<script>
var app2 = angular.module('myApp2', []);
app2.controller('myCtrl2', function($scope, $http) {
$http({
method : "GET",
url : "welcome.htm"
}).then(function mySucces(response) {
$scope.myWelcome = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statusText;
}, function myError(response) {
$scope.content = "Something went wrong";
});
});
</script>
</div>
where i could't even get the scope.satuscode to work.
I'm using Ionic as framework with AngularJS, if someone need extra info to helpmeet just ask and thanks for any idea.
See this FAQ on the Intel XDK web site > https://software.intel.com/en-us/xdk/faqs/app-designer#ajax-jquery-one-fail
If the call is being made successful but you're not getting your $scope to update try wrapping the values you need to update in $timeout .. you can use $scope.apply() but i believe $timeout to be the safer method
<div id="campa_de_sangre" class="upage-content vertical-col left hidden" ng-app="myApp2" ng-controller="myCtrl2">
<p>hola</p>
<h1>{{myWelcome}}</h1>
<p>Status : {{statuscode}}</p>
<p>StatusText : {{statustext}}</p
<p>{{content}}</p>
<script>
var app2 = angular.module('myApp2', []);
app2.controller('myCtrl2', function ($scope, $http, $timeout) {
$http({
method: "GET",
url: "welcome.htm"
}).then(function mySucces(response) {
$timeout(function () {
$scope.myWelcome = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statusText;
}, 0)
}, function myError(response) {
$timeout(function () {
$scope.content = "Something went wrong";
}, 0)
});
});
</script>
</div>

Categories

Resources