In Ionic 6 I'm getting data from a central JSON service that is resolving data on an /:id page like so {{ product.title }}. The central JSON also feeds the wishlist and search facility.
central.json > page/:id
The JSON file is like this:
public product: Product[] = [
{
id:0,
title: 'UK Information',
description: 'Travel tips',
extrainfo:'',
...
I need to use ngx-translate. In the past {{ product.title | translate }} would have pulled the data from assets/i18n/en.json and assets/i18n/fr.json.
Any ideas how I can use ngx-translate to get the dynamic text from strings on a page?
Thanks for any help!
Your object is in an array.
<div>{{ product[0].title || translate }}</div>
Related
i’m trying to configure my deebot robot with mqtt using the Node-Red integration. I managed to configure everything on Node-red, but i can’t split values from the mqtt message.
This is what i get from the( i get many payloads with the same topic):
{"type":"CurrentUsedCustomAreaValues","value":""}
{"type":"CurrentUsedSpotAreas","value":""}
{"type":"CleanReport","value":"stop"}
{"type":"ChargeState","value":"charging"}
{"type":"SleepStatus","value":"1"}
{"type":"LifeSpan","value":{"filter":83.93,"side_brush":-0.42,"main_brush":51.92}}
{"type":"BatteryInfo","value":100,"unit":"%"}
This is how i tried to retrive the data to sensors in configuration.yaml but it's not working, i always get "unknown" sensor value
mqtt:
sensor:
- name: "filter_left"
state_topic: "vacuum/sensors"
unit_of_measurement: "h"
value_template: "{{ value_json['value'].filter }}"
- name: "main_brush_left"
state_topic: "vacuum/sensors"
unit_of_measurement: "h"
value_template: "{{ value_json['value'].main_brush }}"
- name: "side_brush_left"
state_topic: "vacuum/sensors"
unit_of_measurement: "h"
value_template: "{{ value_json['value'].side_brush }}"
- name: "vacuum_battery"
state_topic: "vacuum/sensors"
unit_of_measurement: "%"
value_template: "{{value_json.type.BatteryInfo}}"
Thanks in advance for any help
It looks like your main issue is that the MQTT message isn't valid JSON. If you take that LifeSpan line, for example, and plug it in to the template tool on Home Assistant (http://your-ha-machine.local:8123/developer-tools/template), you could insert the contents of that line (minus the curly braces), like this:
{% set my_test_json = {
"type":"LifeSpan","value":{"filter":83.93,"side_brush":-0.42,"main_brush":51.92}
}
%}
The filter life is at {{ my_test_json.value.filter }}.
You can use that tool to play around with the formatting, and figure out what's wrong with the syntax. You'll probably need to fix the MQTT message on the Node-Red side.
I am using django with templates and trying to send my json response data to the frontend web page. But in the frontend ui i want to show only specific fields of the json response data which i am unable to figure out. Right now i can send the complete json response data and show it in the frontend web page.
Here is my code details -
This function connects to my backend index and gets each document from index and appends it to jsonitems dictionary.
def sampledata(request):
samplecount = requests.get(sampleindex + "/_count", auth=auth, verify=sslcheck)
print(samplecount.json()['count'])
count = samplecount.json()['count']
jsonitems = {}
for item in range(count):
data = requests.get(sampleindex + "/_doc/" + str(item), auth=auth, verify=sslcheck)
jsondata = data.json()
jsonitems[item] = jsondata
print(jsonitems)
context = {'jsonitems': jsonitems}
return render(request, 'samplewebapp/sampledata.html', context)
This is the template view which i am using to render on the frontend web ui.
{% if jsonitems %}
<ul>
{% for k, v in jsonitems.items %}
<table>
<tr><th> Sample data Item </th></tr>
<tr>
<td>{{ v }}</td>
</tr>
</table>
{% endfor %}
</ul>
{% else %}
<p>No CVE data available</p>
{% endif %}
Currently table data 'v' (ie value) shows the complete json data. But i want to show only specific fields from the json data on the frontend (as in v['year'] and v['title'] should show me year and title respectively).
eg. JSON response data
{
"year": 2013,
"title": "Monica Z",
"info": {
"directors": [
"Per Fly"
],
"release_date": "2013-09-13T00:00:00Z",
"rating": 7.3,
"genres": [
"Biography",
"Drama",
"Music"
],
"image_url": "http://ia.media-imdb.com/images/M/MV5BODA5NzUyNDA0M15BMl5BanBnXkFtZTgwODY5MjQwMDE#._V1_SX400_.jpg",
"plot": "Ambitious singer must struggle with her musical career, her love life and to bring up her daughter by herself.",
"rank": 4957,
"actors": [
"Edda Magnason",
"Sverrir Gudnason",
"Kjell Bergqvist"
]
}
Actually there is no json here, because the result of data.json() will be a regular python object (in this case a dictionary). So v (i.e. value) is a dictionary and in the django templates the keys are available as attributes: v.year, for example.
In eleventy, I'm using the 'eleventy-cache-assets' utility to retrieve API data from TMDB and place it in a cache. The JSON is successfully retrieved and stored in the cache. I can also use the Nunjucks dump filter to dump the full JSON to a page. However, I cannot run a for loop over the JSON content. It's behaving as if the data does not exist. I'm likely making a schoolboy error here but I can't see it.
Here's the JS that retrieves the data (successfully).
module.exports = async function () {
try {
// Grabs either the fresh remote data or cached data (will always be fresh live)
let json = await Cache(
`https://api.themoviedb.org/3/movie/upcoming?api_key=${TOKEN}&language=en-GB®ion=GB`,
{
duration: "1d", // 1 day
type: "json",
}
);
return {
films: json,
};
} catch (e) {
return {
films: 0,
};
}
};
Here is how I'm trying to loop through the content. The else condition is returning. When I remove the else condition, nothing is returned (just the empty ul). If I've targeted the node incorrectly, I should have x number of empty li tags, but I don't.
<ul>
{% for film in films %}
<li>{{ results.title }}</li>
{% else %}
<li>This displays if the 'films' collection were empty</li>
{% endfor %}
</ul>
The issue is likely just that you're wrapping the result from the API in an additional object, and eleventy adds an additional wrapper based on the file name of the data file, so you need to modify the way you access the results.
According to the TMDB documentation, the API will return something like this (JSON-encoded):
const json = {
page: 1,
results: [
{/** ... */},
{/** ... */},
{/** ... */},
]
}
Then you're wrapping that result in another object:
return {
films: json,
};
Finally, eleventy makes that data available to templates under a variable name based on the name of your data file — i.e. the file contains your API call. You didn't mention the name of the file, let's assume it lives in your data directory as tmdb.js. That means the variable accessible to your template will look something like this:
const tmdb = {
films: {
page: 1,
results: [
{/** ... */},
{/** ... */},
{/** ... */},
]
}
}
See the documentation on how eleventy parses data files for more information.
This means you can access the results in this way:
<ul>
{% for film in tmdb.films.results %}
<li>{{ film.title }}</li>
{% else %}
<li>This displays if the 'films' collection were empty</li>
{% endfor %}
</ul>
Note also that your original code used {{ results.title }} which isn't defined in your scope, I changed that to use the loop variable film. Also, adjust the tmdb variable to the name of your data file.
I would also recommend not wrapping the response of the API in an additional object (the key films also implies it's a list of films, not the complete API response). It doesn't really add anything and only increases complexity.
I've been stuck with one problem - I'm getting JSON from my service class, I am able to write to the console whole object, I'm able to display root level values, but for the nested values I get [object Object] or nothing at all; depends on various approaches.
I was trying to find a solution across StackOverflow and they all seemed to point for using pipes. Would that be something that you suggest in my case as well?
Here is my code:
In a parent component I simply pass the object to child:
`<app-item *ngFor="let item of items; let i = index" [item]="item[itemId]="i"></app-item> `
On a child class I have
#Input() item: Item;
And finally on a child html template I have the following structure:
<a [routerLink]="[itemId]" class="list-group-item clearfix" routerLinkActive="active">
<div class="pull-left" (click)="stateInfo()">
<h4 class="list-group-item-heading">{{ item.name }}</h4>
<p class="list-group-item-text">Item code : {{ item.code }}</p>
<p class="list-group-item-text">Item tag : {{ item?.tags }}</p>
</div>
</a>
I'vealso tried to extend like {{ item?.tags[i].name }} and various other ways I can think of but none seems to be working.
Tags entity is optional, hence the '?' in a path.
I also attached click event listener, so I can console.log(this.item). This is what I get in the console:
Object:
code: "001"
name: "Kitchen"
tags: Array[2]
0: Object
name: "tag1"
value: "32"
1: Object
name: "tag2"
value: "44"
...
As I understand you have your service as your middle layer between your DB and the view. You inject service in your component, then you call a method that is in your service (from your component). Your service is responsible for getting the data (using http) and mapping it to json. Your component is subscribing to the response, converts json to array and through interpolation is showing to the view. Right?
Tags are an array, so you would need to iterate that array and display them.
First, let's fix an error in your parent template:
[item]="item[itemId]="i"
is wrong. As you can see in your template you are iterating let item of items... so on that same line you can just pass the current item in the itreration, so simply pass that single (current) item:
[item]="item"
Then to iterating the tags. As mentioned it is an array, so you just iterate through it like you did with the items:
<p *ngFor="let tag of item.tags">{{tag.name}}</p>
That should work! :) Here's a Plunker
As a sidenote, is there a special reason why you are iterating through the items and assigning them to a new array and then back to the items array? Why not simply do:
.subscribe(data => {
this.items = data;
})
How to pass a service json data(which already getting from services.js) to filter(filter.js)?
Example:JSON data:
{"name" :"stackoverflow"}
Services.js:
Here i have written service to get json data
{"getjsondataservice" }
Controller:
using "getjsondataservice" service here.
{}i need to get "getjsondataservice" service to filter.jsFilter:{}how should i write that filter?
In output code you should write filter name:
{{ stackoverflow | filter }}
Then the filter will work and you will receive the filtered variable.