Single value in ionic http post param - ionic-framework

Hi I'm new to ionic/angular and I'm reading someone else code and came across the function below in the Service
makePostRequest(100)
public makePostRequest(param) {
return this.http.post('/sample/api', param);
}
Does this mean param is sent as json body or just a value, online documentation just shows json body as the argument not a single value. Can someone help me with this
Thanks in advance.

The post body is sent as serialized parameters as explained here.
In the example you have provided, they are calling the makePostRequest() function and providing an argument of 100. When the makePostRequest() function runs, it takes that value from the argument and sets it as a parameter which is then used to populate the body in the POST request.
You can still send single values as you would multiple values with something similar to this:
sendData() {
const data = {
number: 100
};
return this.http.post('myurl.com', data);
}
Or for multiple:
sendData() {
const data = {
number: 100,
fruit: 'banana'
};
return this.http.post('myurl.com', data);
}
You can of course pass multiple arguments if you have parameters set up to accept them:
sendData(body: { score: number, fruit: string }) {
return this.http.post('myurl.com', body);
}

Related

how to get data from react-query(V4) Promise

I trying react-query for data-fetching (in Typescipt)
in my books, maybe I guess use react-query V3.
but I want to react-query v4
in my books, using react-query...
const useLatestMovie = () => {
return useQuery<AxiosResponse<MovieDetail>, AxiosError>('latestMovie', latestApi)
}
and call function other files,
const { isLoading, data } = useLatestMovie()
but this code isLiading, data not exist
because "Property 'data' does not exist on type 'Promise'."
how do I make this code can work?
You can type your query functions by just specifying the type with the http request.
In the example below we typed the get request with an array of Users. Because the data is typed and returned in the useQuery hook, typescript will implicitly know the type.
async function fetchUsers() {
const { data } = await http.get<User[]>('/users');
return data;
}
export function useUsers() {
return useQuery(['users'], () => fetchUsers());
}
When we use the useUsers hook in our application, the users variable will be of type Users[]
const { data: users } = useUsers();
I try 2 answer..
using query array...
return useQuery<AxiosResponse, AxiosError>(['latestMovie'], latestApi)
type select
return useQuery<MovieDetail, Error>(['latestMovie'], latestApi)

Casting an object in Flutter/Dart returns _HashSet

I am having some problem in Flutter with casting a dynamic to a custom object. I receive JSON as response from a web service, which I store as an instance of my object in a class as dynamic together with some other meta information. When I try to cast that object to my desired class (e.g. LoginReply) I keep getting the following error message: Expected a value of type 'LoginReply', but got one of type '_HashSet<LoginReply>'
Here is my response class that stores the reply object:
class DioResponse {
String? error;
dynamic object;
DioResponse(this.error, this.object);
bool get isSuccessful => error == null || error!.isEmpty;
T get<T extends dynamic>() {
print("Object: $object");
return object.cast<T>();
}
}
I serialize the JSON response like this:
LoginReply _serializeResponse(Map<String, dynamic> json) {
LoginReply reply = LoginReply.fromJson(json);
if (!reply.header!.successful) {
errorMessage.value = "${reply.header!.errorCode}: ${reply.header!.errorMessage}";
return LoginReply();
}
AppConfig.persistString("token", reply.token!);
return reply;
}
And here is how I try to access the DioReponse.object / LoginReply:
DioResponse response = await handler.post(Globals.nodeAddress, ......);
if (response.isSuccessful) {
//LoginReply reply = response.get<LoginReply>();
print("Object: ${response.object}");
LoginReply reply = response.object as LoginReply;
The print output on the second last line prints: Object: {Instance of 'LoginReply'} which makes the whole error even harder to understand for me.
The problem was in the closure that was passed as parameter to the post function. So it really returned a Set. I pass a function to the DioHandler class that is called there and then it just works the way it should.

tronweb : how to get return value using tronweb contract send function

let contract = await window.tronWeb.contract().at(config.contract);
let result = await contract.methods.depositTron()
.send({callValue:amount*1000000})
.then(output=>transaction = output);
console.log("result", result);
I tried to get the result of depositTron method, but returned hash value.
how should I do?
please help me.
Functions invoked by transactions only return value within the EVM (usually when called from another contract).
The hash returned from the send() JS function, is the transaction hash.
You can workaround this by emitting an event log within the contract. Then you can get the value or read emitted logs from the transaction receipt (emitted in JS after the transaction is mined).
Solidity:
contract MyContract {
event Deposit(uint256 indexed amount);
function depositTron() external payable {
emit Deposit(msg.value);
}
}
JS:
contract.methods.depositTron().send({callValue:amount*1000000})
.on('receipt', (receipt) => {
console.log(receipt.logs);
})

Parse Server SDK - Include Object method doesn't work for fetching the whole object in flutter

I was using parse server sdk in my app for database.
I have three class in my Back4App Dashboard which are "_User", "Office", "Office_Members".
In Office_Members class it has following columns,
user_id (Pointer to _User)
office_id (Pointer to Office)
count
To fetch the data including Pointer to _User as well from Office_Members, I am using following code,
QueryBuilder<ParseObject> parseQuery = QueryBuilder<ParseObject>(ParseObject("Office_Members"))
..whereEqualTo("office_id", ParseResponse_OfficeObject)
..includeObject(["user_id "]);
ParseResponse apiResponse = await parseQuery.query();
Output :
Payload : [{"className":"Office_Members","objectId":"twpDY51PUK","createdAt":"2020-08-14T09:58:59.775Z","updatedAt":"2020-08-14T09:58:59.775Z","office_id":{"__type":"Pointer","className":"Office","objectId":"4dkfSMrwBI"},"user_id":{"__type":"Pointer","className":"_User","objectId":"Hx5xJ5ABxG"},"count":1}]
In my payload response i am not getting whole user_id pointer response.
So can anybody help me that what i might be doing wrong?
Thanks.
The data should be included.
The logging function simply does not print the data of pointers.
The data should be included. The print function not print the data of pointers.
You can print it out directly for testing purposes, E.g.
response.results[0].get('user_id').get('name')
Evaluation Expression E.g.
In your model u can access at same way, E.g
Call Model
if(response.success){
return response.results.map((p) => Example.fromParse(p)).toList();
} else {
throw ParseErrors.getDescription(response.error.code);
}
Model
import 'package:parse_server_sdk/parse_server_sdk.dart';
class Example {
Example({this.id, this.name});
Example.fromParse(ParseObject parseObject) :
id = parseObject.objectId,
name = parseObject.get('user_id').get('name');
final String id;
final String name ;
#override
String toString() {
return 'Example{id: $id, name: $name}';
}
}
Why not simply use cloud code ? I'm not to familiar with flutter but I can suggest you this alternative solution.
Write a function like this.
Parse.Cloud.define("fetchMemberAndUser", async (request) => {
//Pass in ParseResponse_OfficeObject ID as parameter
var objectId = request.params.id;
//Now do a simple get query
var query = new Parse.Query(Parse.Object.extend("Office_Members"));
//Using .includes to get the user profile object
query.include("user_id");
//This will return Office_Memebers Object along with user profile
return query.get(objectId,{useMasterKey:true});
}

GWT JSNI returning string from JSNI function

EDIT I think because it is an asychronous call that when I call the method data has not been set yet.
String theData = getData("trainer") // not set yet
I have the following JSNI function. The if I call this function it returns an empty string, however the console.log before it show that data is there. Seems data cannot be returned for some reason.
public native String getData(String trainerName)/*-{
var self = this;
$wnd.$.get( "http://testdastuff.dev/trainerstats", { trainer: trainerName} )
.fail(function() {
$wnd.console.log("error");
})
.done(function( data ) {
console.log("DATA IS: " + data);
return data;
});
}-*/;
Your thought that it is a asynchronous call is correct.
The return of the callback passed to done is not returned to the original call you made.
If you used the following code, you'll get 2 messages in the console, in the first you'll get empty data, and in the second, the correct data.
String theData = getData("trainer");
consoleLog("The data is " + theData);
// suppose consoleLog as a native function to console.log
Thus you should probably do your callback like this.
.done(function( data ) {
console.log("DATA IS: " + data);
theData = data; // if theData is within the same scope and you want to store
doSomethingWith(theData); // <-- here you can interact with theData
})
The doSomethingWith(theData) could even be an invocation to a Java method.