Nativescript bind a response to observable - android

I am new to Nativescript and trying to build an Android App.I am sending a POST request and getting an proper response.But the problem is I can not bind the response data to Observable.I am trying to bind the data[0].value to price in my Viewmodel.But I have failed to do that.But if I try to set hardcoded data like this Viewmodel.set("price","1000$") then it's ok.But i can not set response data.
var fetchModule = require("fetch");
var Observable = require("data/observable").Observable;
var ObservableArray = require("data/observable-array").ObservableArray;
var data;
var person;
var priceFromResponse;
function ModelViewModel() {
var viewmodel = new Observable();
var Viewmodel =new Observable();
viewmodel.get=function(model){
data = model;
}
var viewModel = new ObservableArray();
viewModel.load = function() {
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) {
for(var i=0;i<data.length;i++){
viewModel.push({
model: data[i].product,
});
};
priceFromResponse =data[0].value;
}).then(function(price){
})
}
viewModel.empty = function() {
while (viewModel.length) {
viewModel.pop();
}
};
**Viewmodel.set("price",priceFromResponse);**
return [viewModel,viewmodel,Viewmodel];
}
module.exports = ModelViewModel;

Related

Cloud function sending json as map

I am sending json to cloud function via postman and it works fine, how can I send same json as map to cloud function:
Sending via postman:
{
"data": {
"users": [
{
"phone": "55512345"
},
{
"phone": "972525276676"
},
{
"phone": "55512347"
}
]
}
}
Sending via android:
private fun addMessage(): Task<String>? {
val usr1 = User("55512345")
val usr2 = User("972525276676")
val usr3 = User("55512347")
val userList = listOf(usr1,usr2,usr3)
val data: MutableMap<String, Any> = HashMap()
data["users"] = userList
functions.getHttpsCallable("getUsers")
.call(data)
.addOnFailureListener {
Log.d("DTAG", it.toString())
}
.addOnSuccessListener {
Log.d("DTAG","Ok: ${it.data.toString()}")
}
return null
}
Where user is:
data class User(var phone:String)
Cloud function:
exports.getUsers = functions.https.onRequest(async (request, response) => {
const data = request.body.data;
if (data !== null && data.users !== null) {
const users = data.users;
const phonelist = users.map(user => user.phone.toString());
const userlist = []
const snapshot = await db.collection("users").get()
snapshot.docs.forEach((userDoc) => {
const phone = userDoc.get("phone")
if(phone === null) return;
const isContain = phonelist.reduce((acc, num) => acc || phone.includes(num), false)
if(isContain) {
userlist.push(userDoc.data())
}
})
response.status(200).json({result: userlist})
} else{
response.sendStatus(403)
}
});
Error:
Object cannot be encoded in JSON: User(phone=55512345)
The error is telling you that the client SDK doesn't know what to do with the User class. You'll have to build a Map<String, Object> out of the data.
val userMap1 = mapOf("phone" to "55512345")
...
val userList = listOf(userMap1, ...)

Passing custom object through method channel flutter

I am trying to pass a custom object which is of type User from native platform to Flutter. The User class is part of a library and not accessible directly for editing. Here is my android and iOS code implementation for the same. Problem is I am not able to find a solution on how to pass this object through method channels in such a way that I can parse it in the Dart code easily.
Android part:
private fun loginUser(uid: String, apiKey: String, result: MethodChannel.Result) {
MyChat.login(uid, apiKey, object : MyChat.CallbackListener<User>() {
override fun onSuccess(user: User) {
Log.e(TAG, user.toString())
result.success(hashMapOf("RESULT" to true, "AVATAR" to user.avatar,
"CREDITS" to user.credits,
"EMAIL" to user.email,
"LAST_ACTIVE" to user.lastActiveAt,
"NAME" to user.name,
"ROLE" to user.role,
"STATUS" to user.status,
"STATUS_MESSAGE" to user.statusMessage).toString())
}
override fun onError(p0: MyChatException?) {
Log.e(TAG, p0?.message)
result.error("FAILED", "Unable to create login", null)
}
})
}
iOS implementation:
func loginUser(result: #escaping FlutterResult, uid: String, apiKey: String){
MyChat.login(UID: uid, apiKey: apiKey, onSuccess: { (user) in
// Login Successful
let data: [String: Any] = ["RESULT":true,
"AVATAR":user.avatar!,
"CREDITS": user.credits,
"EMAIL": user.email!,
"LAST_ACTIVE":String(user.lastActiveAt),
"NAME":user.name!,
"ROLE":user.role!,
"STATUS":user.status.rawValue,
"STATUS_MESSAGE":user.statusMessage]
let jsonData = try? JSONSerialization.data(withJSONObject: data, options: [.prettyPrinted])
result(String(data: jsonData!, encoding: .ascii))
}) { (error) in
// Login error
result(FlutterError(code: "FAILED", message:"Login failed with exception: " + error.errorDescription, details: nil))
}
}
My dart code:
Future<String> isUserLoggedIn() async {
String status = "";
try {
final String result = await platform
.invokeMethod('loginUser', {"UID": UID, "API_KEY": API_KEY});
print(result); //How to parse?
status = "Hello";
} on PlatformException catch (e) {
print("Exception");
status = e.message;
}
return status;
}
You can pass data in hash map.
In Android:
result.success(hashMapOf(
"CREDITS" to user.credits,
"EMAIL" to user.email,
...
))
In iOS:
let data: [String: Any] = [...]
result(data)
In Flutter:
final result = await platform.invokeMethod<Map<String, dynamic>>('loginUser', ...);
final credits = result['CREDITS'] as String;
final email = result['EMAIL'] as String;
...
you can use invokeMapMethod which is an implementation of invokeMethod that can return typed maps.
like this :
final result = await platform.invokeMapMethod('loginUser', ...);
or you can pass json object as string like that :
in android
platform.success(
"{\"CREDITS\":\"${user.credits}\",\"EMAIL\":\"${user.email}\",\"LAST_ACTIVE\":\"${user.lastActiveAt}\"}"
)
in flutter
var result = await methodChannel.invokeMethod('loginUser' , '');
var json = json.decode(result);
var credit = json['CREDITS'];
var email = json['EMAIL'];
var lastActive = json['LAST_ACTIVE'];

node.js-Cannot read property 'email' of undefined

When I run the code, it shows "User was registered successfully", but followed with "Cannot read property 'email' of undefined".
I try to fix the error, but failed. I think it may be some error in userRecord, but I checked many times and can't find what's the problem.
Here is my code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var admin = require("firebase-admin");
var userAccountRequests = (io) =>{
io.on('connection',(socket)=>{
console.log(`Client ${socket.id} is connected`);
detectDisconnection(socket,io);
registerUser(socket,io);
});
};
I think there may be some error here. It can show the "successfully" message, but I think I have defined email.
function registerUser(socket,io){
socket.on('userData',(data)=>{
admin.auth().createUser({
email:data.email,
displayname:data.userName,
password:data.password
})
.then((userRecord)=>{
console.log('User was registered successfully');
var db = admin.database();
var ref = db.ref('users');
var userRef = ref.child(encodeEmail(data.email));
var data = {
data:admin.database.ServerValue.TIMESTAMP
};
userRef.ser({
email:data.email,
userName:data.userName,
dataJoined:date,
hasLoggedIn:false
});
//send message to Client
Object.keys(io.sockets.sockets).forEach((id)=>{
if(id == socket.id){
var message = {
text:'Success'
}
io.to(id).emit('message',{message});
}
});
}).catch((error)=>{
Object.keys(io.sockets.sockets).forEach((id)=>{
console.log(error.message);
if(id == socket.id){
var message = {
text:error.message
}
io.to(id).emit('message',{message});
}
});
});
});
}
function detectDisconnection(socket,io){
socket.on('disconnect',()=>{
console.log('Client has disconnected');
});
}
function encodeEmail(email) {
return email.replace('.',',');
}
module.exports = {
userAccountRequests
}
The 'data' object is only active within the function in 'on', this code:
socket.on('userData',(data)=>{
admin.auth().createUser({
email:data.email,
displayname:data.userName,
password:data.password
})
At the end of this function, 'data' is no longer defined. The 'then' that follows is using 'userRecord' instead.
You should change your 'data' references to 'userRecord', like this:
function registerUser(socket,io){
socket.on('userData',(data)=>{
admin.auth().createUser({
email:data.email,
displayname:data.userName,
password:data.password
})
.then((userRecord)=>{
console.log('User was registered successfully');
var db = admin.database();
var ref = db.ref('users');
var userRef = ref.child(encodeEmail(userRecord.email));
// not sure what this is about
var data = {
data:admin.database.ServerValue.TIMESTAMP
};
userRef.ser({
email:userRecord.email,
userName:userRecord.userName,
dataJoined:date,
hasLoggedIn:false
});
//send message to Client
Object.keys(io.sockets.sockets).forEach((id)=>{
if(id == socket.id){
var message = {
text:'Success'
}
io.to(id).emit('message',{message});
}
});
}).catch((error)=>{

Repeating push notification in back4app

I am sending push notification from iOS and Android both by calling a cloud function, and in each device I am getting 5 times a single push notification. I am using parse database hosted on back4app.
Cloud code is given below:
Parse.Cloud.define("push", function (request, response) {
var query = new Parse.Query(Parse.Installation);
var userID = request.params.user;
var message = request.params.message;
var notificationType = request.params.notificationType;
var user = new Parse.User();
user.id = userID;
query.equalTo('user', user);
query.equalTo("allowPush", true);
Parse.Push.send({
where: query,
data: {
alert: message,
sound: 'default',
"type": notificationType
}
}, { useMasterKey: true });
});
Try to call reponse.success and response.error functions in the end of your cloud code function. Since your client code is not receiving the feedback if the call worked or not it is probably attempting to send again.
Parse.Cloud.define("push", function (request, response) {
var query = new Parse.Query(Parse.Installation);
var userID = request.params.user;
var message = request.params.message;
var notificationType = request.params.notificationType;
var user = new Parse.User();
user.id = userID;
query.equalTo('user', user);
query.equalTo("allowPush", true);
Parse.Push.send({
where: query,
data: {
alert: message,
sound: 'default',
"type": notificationType
}
},
{
success: function () { response.success(); },
error: function(err) { response.error(err); },
useMasterKey: true
});
});

Angular login parse json

I am making an android app in ionic. I am working on the login page. I want to check for the return json value and redirect user to other page or display error.
My code:
.controller('loginCtrl', function ($scope, $stateParams, MyServices, $location) {
$scope.login = {};
$scope.login.username = "";
$scope.login.password = "";
var loginsuccess = function (data, status) {
if (data['valid'] != "false") {
// $state.go('app.playlists');
alert('success');//Not working
}
else
{
$ionicPopup.alert({
title: 'Login failed!',
template: 'Please check your credentials!'
});
};
};
$scope.loginbutton = function () {
MyServices.login($scope.login).success(loginsuccess);
};
})
json returned from server:
{"valid":"true"}

Categories

Resources