How to read attribute "name" of my json array in Ionic - arrays

json array localstorage format
Hello, I'm developing an ionic app. I'm new in Ionic and Typescript.
As you can see in the image below I'm parsing from an API my data in a json array.
On ts file I'm writing this code
`
public categoryDetails:any;
const datacat = JSON.parse(localStorage.getItem('categoryData'));
this.categoryDetails = datacat.categoryData;`
And in my html file when I write this
<h1 class="business-top">Business of the category {{categoryDetails.name}}</h1>
I get the error message "TypeError: Cannot read property 'name' of undefined"
I know that I don't read the attribute "name" correctly. How can I do this one?
Moreover, how can I display Businesses which associate with the spesific term_id of the category?

In this example you need to do that
<h1 class="business-top">Business of the category {{categoryDetails?.name}}</h1>
public categoryDetails: any;
this.categoryDetails = localStorage.getItem('categoryData');
or you can use ionic storage. it is better if you are using ionic.
https://ionicframework.com/docs/storage/
import { Storage } from '#ionic/storage';
export class MyApp {
public categoryDetails: any;
constructor(private storage: Storage) { }
...
// set a key/value
storage.set('categoryData', 'Max');
// Or to get a key/value pair
storage.get('categoryData').then((val) => {
this.categoryDetails = val;
});
}

I finally fingured it out.
#Kilomat thanks for your help and your advice about using ionic storage. That saved me from futured problems.
About my json file that's what I did.
In my HTML code
<ion-grid no-margin>
<h1 class="business-top">Επιχειρήσεις της κατηγορίας {{businessData.name}} {{businessData.term_id}}</h1>
<ion-list>
<ion-item class="col col-50" *ngFor="let c of BusinessCategoryDetails" text-wrap (click)="product(c)">
<div *ngIf="c.term_id == businessData.term_id">
<h2>{{c.post_title}} {{c.term_id}}</h2> <img width="80" height="80" src="{{c.guid}}">
</div>
</ion-item>
</ion-list>
</ion-grid>
And in my TS code
`var businessCategory: categories = navParams.get("businessCategory");
console.log(businessCategory); /exports the Selected category/
var newData = JSON.stringify(businessCategory);
this.businessData = JSON.parse(newData);`
Which takes properties and values from my previous category page. TS code
`categories: [categoryDetails] = null;
gotobusiness(category: categories){
this.navCtrl.push(BusinessPage, { businessCategory: category});
}`

Related

how to iterate arrays in angular 12? (typescript firebase)

I am learning typescritp and I have already been around the web a thousand times and I did not find anything clear about how to iterate arrays
with ngfor to display on screen ...
below an image of how I am saving the data in firestore.
I would like to show each array eg "title", "date" like the image below (with documents without arrays there is no problem)
datos firebase
my service:
listarNotificacionSrv3(): Observable<any> {
return this.firestore.collection('notificacion').get();}
my component
listarNotificacion2() {
this.subscription = this.notificacionService
.listarNotificacionSrv3()
.subscribe((doc) => {
console.log('doc', doc);
this.listarnotificacion2 = [];
doc.forEach((element: any) => {
this.listarnotificacion2.push({
id: element.payload.doc.id,
...element.payload.doc.data(),
});
});
});}
my html:(Here I don't know how to iterate the arrays in my particular case)
<div class="card mt-3" *ngFor="let datos of listarnotificacion2 | keyvalue ">
<h5>ver: {{datos}}</h5>
</div>
the expected jajaja:
view data in screen
returns on screen with snaphshotChanges ()
returns on screen
From already thank you very much!
cheers!
sorry for my inglish...

Iterating to an object from firebase angular data model

I want to get all type from the /type in my angualr firebase app.
I have written a provider function
getAllDetails() {
let fn = firebase.database().ref('/type').on("value", function (snapshot) {
console.log(snapshot.val());
return snapshot.val();
});
return fn;
}
and on the main class i am trying to pull all data in the Array
type: Array<any> = [];
ngOnInit() {
this.type.push(this.db.getAllDetails());
}
But it is not pulling any Data in the ngFor Tag in the html , in the console the objects are getting printed. Attached images.
<ion-select>
<ion-option *ngFor="let item of type ">{{item.type}}</ion-option>
</ion-select>
enter image description here

Browse an array of months with 'ngFor' directive

My lack of knowledge in Angular 2 and typescript led me to this issue :
I want a datatable (already imported well) with all the months of the year on abscissa, and some DB objects on the ordinate (this is OK).
I don't know how and where to declare my list of months and how to browse it in my html.
A this moment, I have this :
Component.ts :
public months= {
1:'Janvier',
2:'Février',
3:'Avril',
etc...
12:'Decembre'
};
Component.html
<td *ngFor="let month of months">{{month}}</td>
Could you help me making it work (displaying at least a raw of months) and as clean as possible ? I'm pretty sure declaring a list of months directly in the class is not a good thing...
Thank you for reading
You have to make an array of months. Currently you have an object.
public months = ["Janvier", "Février", "Avril"...];
Or if you really want to have an object, you can implement custom pipe:
import { Injectable, Pipe } from '#angular/core';
#Pipe({
name: 'keyObject'
})
#Injectable()
export class KeyObjectPipe {
transform(value, args:string[]):any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}
}
And then you can use it as:
<td *ngFor="let month of months | keyObject">{{month.value}}</td>
Alternatively, you can use this way
months= [
{ 'id' :1 , 'name':'Janvier'},
{ 'id' :2 , 'name':'Février'},
{ 'id' :3 , 'name':'Avril'}
];
Accessing it in the ngFor as below
<div *ngFor="let month in months">
{{month.name}}</div>
</div>
Why not just use indexing in your view?
In your TS:
months = ["Janvier", "Février", "Avril"...];
In your HTML:
<div *ngFor="let month of months; let i = index">
<p>Month(string): {{month}}</p>
<p>Month(number): {{i+1}}</p>
</div>

How to retrieve nested json object data with Ionic

I am working with the api from The Movie Database. In my Ionic project I was able to make a http request to pull in some data for a movie. However the json object is a nested json object, so I am having some trouble trying to access the genres of a movie:
For the purpose of this question I will display 1 nested json object:
I want to show the information like so -> Genre: Action - Comedy - Drama
My code for the controller is the following:
$scope.init = function(){
MovieService.getMovieById($stateParams.id).then(function(data){
$scope.trending_movie = data;
console.log($scope.trending_movie);
$scope.genres = data.genres;
console.log($scope.genres);
});
}
If I do this bit of code:
$scope.genres = data.genres;
It just returns met the json object of the genres like so:
The thing is now that I am able to read out the genres but because I access the data with a ng-repeat it will show like this:
How to get the genres on 1 line without having to repeat the word "Genre"?
Here is my html code:
<div ng-repeat="genre in genres">
<p class="movie-info-p">Genre: {{genre.name}}</p>
</div>
you should get "Genre:" out of your ng-repeat and if you want your genres to be in the same line, you shouldn't put them in tag.
There is this solution:
<div> Genre:
<div ng-repeat="genre in genres">
<span class="movie-info-p">{{genre.name}}</span>
</div>
</div>
Another solution is to generate this string in the controller with a for loop and send it to the view

WP Rest API Get Featured Image

I am building a relatively simply blog page that uses the WP Rest Api and AngularJs to show the data on the front-end.
On my home page I want to return the title, followed by the featured image, followed by the excerpt. I have pulled the title and excerpt in fine it seems that in the JSON the featured image is a media Id. What is the best way to pull this data in on the fly?
I have seen various things around the internet that use PHP functions but I think the best way to do it is within a angular controller, just looking for some advice on exactly what the controller would be
List View HTML
<ng-include src=" dir + '/form.html?v=2' "></ng-include>
<div class="row">
<div class="col-sm-8 col-lg-10 col-lg-push-1 post">
<div class="row-fluid">
<div class="col-sm-12">
<article ng-repeat="post in posts" class="projects">
<a class="title" href="#/post/{{post.slug}}"><h2>{{post.title.rendered}}</h2></a>
<p ng-bind-html="post.excerpt.rendered | to_trusted"></p>
</article>
</div>
</div>
</div>
</div>
Controller
.controller('listPage',['$scope','Posts', function($scope,Posts){
$scope.refreshPosts = function(){
Posts.query(function(res){
$scope.posts = res;
});
};
$scope.refreshPosts();
// CLEARFORMFUNCTION
$scope.clear = function(){
$scope.$root.openPost = false;
jQuery('#save').modal('hide');
};
// SAVEMODALOPEN/COSE
$scope.openSaveModal = function(){
jQuery('#save').modal('show');
}
$scope.closeSaveModal = function(){
jQuery('#save').modal('hide');
}
// DATEFUNCTION
$scope.datify = function(date){
$scope.date = newDate(date);
return $scope.date.getDate()+'/'+$scope.date.getMonth()+'/'+$scope.date.getYear();
};
}])
You could also modify the JSON response with PHP. This returns just what I need and is very fast (Using _embed is very slow in my experience)
I have the following code in a plugin (used for adding custom post types), but I imagine you could put it in your theme's function.php file.
php
add_action( 'rest_api_init', 'add_thumbnail_to_JSON' );
function add_thumbnail_to_JSON() {
//Add featured image
register_rest_field( 'post',
'featured_image_src', //NAME OF THE NEW FIELD TO BE ADDED - you can call this anything
array(
'get_callback' => 'get_image_src',
'update_callback' => null,
'schema' => null,
)
);
}
function get_image_src( $object, $field_name, $request ) {
$size = 'thumbnail'; // Change this to the size you want | 'medium' / 'large'
$feat_img_array = wp_get_attachment_image_src($object['featured_media'], $size, true);
return $feat_img_array[0];
}
Now in your JSON response you should see a new field called "featured_image_src": containing a url to the thumbnail.
Read more about modifying responses here:
http://v2.wp-api.org/extending/modifying/
And here's more information on the wp_get_attachment_image_src() function
https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/
**Note: Don't forget <?php ?> tags if this is a new php file!
Turns out, in my case, there is a new plugin available that solves this without having to make a secondary request. See my recent Q:
WP Rest API + AngularJS : How to grab Featured Image for display on page?
If you send the ?_embed param to the query, it will return more information in the response, like images, categories, and author data.
const result = await axios.get(`/wp-json/wp/v2/my-post-type?_embed`);
// Featured Image
result.data._embedded['wp:featuredmedia'][0].source_url;
// Thumbnail
result.data._embedded['wp:featuredmedia'][0]['media_details']['sizes']['medium']['source_url']

Resources