Typescript - Angular http post - json

I am building an autocomplete functionality.
1) The backend RESTful service returns following response for partially entered keyword.
JSON response
{
"suggest": {
"resultsuggest": [
{
"text": "Ke",
"offset": 0,
"length": 2,
"options": [
{
"text": "Kevin Johnson",
"_index": "customernames",
"_type": "_doc",
"_id": "1",
"_score": 3
}]
}
]
}
}
2) In Angular application, what should I do to extract the options array from the JSON response and return it back for this fetch function??
Note - I want to use the Promise instead of Observable.
fetch(params?: HttpParams): Promise<any> {
const query = params.get('query');
const headers = new HttpHeaders().set("Content-Type", "application/json");
let postData = "{ \"_source\": \"suggest\", \"suggest\": {\"resultsuggest\" : { \"prefix\" : \""+query+"\",\"completion\" : { \"field\" : \"suggest\", \"size\" : 5 }}}}";
return this._http.post<any[]>('http://127.0.0.1:9200/customernames/_search?pretty',postData, {headers})
.pipe(map(result=> {
// what should I do to extract the Options array from the JSON response and return it back in this fetch function??
return ????;
}),
delay(400)
).toPromise();
}
Appreciate your help!
thanks!
Updated:
1) JSON response is fixed.
2) changed return this._http.post<any> to return this._http.post<any[]>

As Arcteezy suggested, the following worked
map(result=> { return result.suggest.resultsuggest[0].options; }

Related

getting data from an array of objects inside array JSON data

I have trouble taking data from an API set. The body if viewed in Postman / Insomnia is as follows
{
"responses": {
"log": [
{
"id": 123,
"date": "2022-01-01T01:12:12.000Z",
"type": "online",
"details": [{
"detailId": "123-1",
"note": "success",
}]
},
{
"id": 124,
"date": "2022-01-01T01:12:12.000Z",
"type": "offline",
"details": [{
"detailId": "123-2",
"note": "failed",
}]
}
]
}
}
I want to take all data from log, as well from details. I used
adapt(item: any) {
return {
id: item.id,
date: item.date,
details: {
detailId: item.details.detailId,
note: item.details.note,
},
};
}
this returns id and date just fine. I also have a query to filter it based on type (online or offline), basically adding &type= into the API. It works for the online, but it returns detailId is undefined for offline (I used the same body, adapter and API minus the query for both data)
details is an array of object if you want to adapt it you need to do it iteratively.
adapt(item: any) {
const details = item.details.map(d => {detailId: d.id, note: d.note, …});
return {
id: item.id,
date: item.date,
details
};
}
Found the answer, apparently to make sure that I can get every value is to add ? after the [0], so it should be
details: {
detailId: item.details[0]?.detailId,
note: item.details[0]?.note,
},

How to retrieve array inside an array into a table using vue js

i want to retrieve some array inside an array but i dont know how, please read my explanation first
here is my json response
{
"Value": [
{
"id": "5ff97d740e788778dd66ee25",
"id_order": "ORD-434183",
"nama_pelanggan": "Herman",
"total": 80000.0,
"jumlah_item": 4.0,
"cart": [
{
"id_cart": "CART-112010",
"nama_produk": "Ayam Bakar",
"jumlah": 4.0,
"harga": 20000.0,
"subtotal": 80000.0,
"notes": "ga ada"
}
],
"admin_no": "ADM-431525",
"admin_name": "Admin",
"created_at": "2021-01-09 16:55:00",
"updated_at": "2021-01-09 16:55:00"
}
],
"Status": true,
"Messages": [
{
"Type": 200,
"Title": "TotalRows",
"Message": "1"
}
]}
as you can see the value of "value" is an array and in that array also have an array "cart"
i want to retrieve this array "cart" and put it in a table
here is how i retrieve the response using vue js Mapping an Array to Elements with v-for
var vm = new Vue({
el: '#app',
data: {
list: {
items: [],
},
}
var formData = new FormData();
formData.append('filterparams', JSON.stringify(filters));
formData.append('display', JSON.stringify(_self.list.config.display));
formData.append('auth', sessionStorage.getItem("token"));
_self.$http.post(hostapi + 'order/GetByParamsHistory', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
var obj = response.data;
_self.list.items = obj.Value; // the value from array "Value"
here is the table html code
and now I don't know how to insert an existing array in the array into the html table
You can access the array on the basis of the array index.
Suppose, if list contains the json response's value field then you can access it like.
list['0'].cart.

get json value object from mongodb

I have formData node that has dynamic jsonObject value in mongodb
{
"_id": {
"$oid": "5a71fea0f36d2848ae4f8f0a"
},
"formData": {
"pages": [
{
"name": "page1",
"questions": [
{
"type": "comment",
"name": "about",
"title": "Please tell us about your main requirements "
}
]
}
]
},
"editorId": "59678e58f36d2842f777bc48",
"datetimeSubmit": "2018/01/15"
}
I write a node API to fetch the data from mongodb, it only display ids, editorI and datetimesubmit nodes, but it ignores the formData(jsondata) field.
const Model = require('./myModel');
module.exports = {
getData: function (callback) {
Model.find({}, (err, jsonObj) => {
callback(null, {
data: jsonObj
})
})
}
}
looks like the model.find() doesn't return jsonObject value?
thanks
got my own question fixed, basically, i should also define the data type as JSON in schema, otherwise, will be ignored.

How to remove Task json properties in Nancy.Response.AsJson

I've made one of my API endpoints and inner logic asynchronous and when previously I've used Response.AsJson(Foo.bar()) , it would return the json representation normally, but now I see this appended to it:
{
"result": [
{
"id": "59d680cc734d1d08b4e6c89c",
"properties": {
"name": "value"
}
}
],
"id": 3,
"exception": null,
"status": 5,
"isCanceled": false,
"isCompleted": true,
"isCompletedSuccessfully": true,
"creationOptions": 0,
"asyncState": null,
"isFaulted": false
}
But I want it to be like this:
"id": "59d680cc734d1d08b4e6c89c",
"properties": {
"name": "value"
}
As I understand, it's because I've wrapped my object in a Task , but I can't figure out, how with Nancy framework, which I use the Response.AsJson, to make it so the properties are excluded. I can obviously omit the Response.AsJson of the returned object, but then response is no longer Json if requesting through web-browser for example.
For further example
NancyModule for routing API:
public ItemCatalogModule(IItemCatalog itemCatalog) : base("/itemCatalog")
{
Get("/fetch/{id}", async parameters =>
{
var id = (string) parameters.id;
var response = await Response.AsJson(itemCatalog.GetItem(id));
return response;
});
}
How the interface looks like of ItemCatalog:
public interface IItemCatalog
{
Task<Item> GetItem(string id);
}
You shoud do this :
public ItemCatalogModule(IItemCatalog itemCatalog) : base("/itemCatalog")
{
Get("/fetch/{id}", async parameters =>
{
var id = (string) parameters.id;
return Response.AsJson(await itemCatalog.GetItem(id));
});
}

Getting key and value from JSON with angular2

I am looking for best solution how to work with JSON in my angular2 app.
My JSON is:
{
"rightUpperLogoId": {
"id": 100000,
"value": ""
},
"navbarBackgroundColorIdCss": {
"id": 100001,
"value": ""
},
"backgroundColorIdCss": {
"id": 100002,
"value": ""
},
"translationIdFrom": {
"value": "90000"
},
"translationIdTo": {
"value": "90055"
}
}
This JSON is something like configuration file for UI of app. In my application, I want to get id from rightUpperLogoId, it is 100000. With this id I need to do GET task on my backend REST api and the returned value I would like to set to value. Thank you
You could leverage Rx operators like the flatMap one with Observable.forkJoin / Observable.of.
Here is a sample:
this.http.get('config.json')
.map(res => res.json())
.flatMap(config => {
return Observable.forkJoin(
Observable.of(config),
// For example for the request. You can build the
// request like you want
this.http.get(
`http://.../${config.rightUpperLogoId.id}`)
);
})
.map(res => {
let config = res[0];
let rightUpperLogoIdValue = res[1].json();
config.rightUpperLogoId.value = rightUpperLogoIdValue;
return config;
})
.subcribe(config => {
// handle the config object
});
This article could give you more hints (section "Aggregating data"):
http://restlet.com/blog/2016/04/12/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-2/