React-native Flatlist doesn't list my json local file - json

I met an issue with my Flatlist in Board.js which doesn't display the content of a json data located inside a file BoardData.js.
However I ve console.log the import of the BoardData and seems the json isfine.But when Istart to read on some data via the flat list. the data are undefined.
See my BoardData.js file :
var BoardData = [
{
"id":"1",
"status": "declared",
"date": "03-DEC-2019",
"category": "Fuite d'eau",
"event_info": "Contact du Plombier",
"adress": "2 rue de la queuleuleu, 31200 Toulouse",
"imageUrl": "..data/photo/photo_123456.webp"
},
{
"id":"2",
"status": "run",
"date": "12-JAN-2020",
"category": "eclairage",
"event_info": "Contact du Plombier",
"adress": "3 impasse alphonse-daudet, 31700 Blagnac",
"imageUrl": "../data/photo/photo_234459.jpg"
},
{
"id":"3",
"status": "declared",
"date": "20-FEB-2020",
"category": "chaussee",
"event_info": "Contact du Plombier",
"adress": "50 avenue de Fronton, 31140 Aucamville",
"imageUrl": "../data/photo/photo_458049.jpg"
},
{
"id":"4",
"status": "closed",
"date": "04-DEC-2019",
"category": "Poubelle",
"event_info": "Contact du Plombier",
"adress": "3 rue de la queuleuleu, 31200 Toulouse",
"imageUrl": "../data/photo/photo_123456.webp"
},
{
"id":"5",
"status": "closed",
"date": "13-JAN-2020",
"category": "Ascenceur",
"event_info": "Contact du Plombier",
"adress": "4 impasse alphonse-daudet, 31700 Blagnac",
"imageUrl": "../data/photo/photo_234459.jpg"
},
{
"id":"6",
"status": "run",
"date": "21-FEB-2020",
"category": "chaussee",
"event_info": "Contact du Plombier",
"adress": "52 avenue de Fronton, 31140 Aucamville",
"imageUrl": "../data/photo/photo_458049.jpg"
},
];
module.exports = BoardData;
Then see my code to render my FlatList:
import React, { Component } from 'react';
import {
FlatList, ScrollView, StyleSheet, Platform, View, Image, Dimensions, TouchableOpacity,
} from 'react-native';
import {Card, CardItem, Left, Right, Thumbnail, Title, Subtitle} from 'native-base';
import BoardData from '../data/BoardData.js'
console.log ('BoardData : ', BoardData)
export default class BoardScreen extends Component {
constructor(){
super();
this.state = {
boarderstatus: 'declared',
myCases: [],
}
}
componentDidMount () {
this.setState({myCases:BoardData })
}
// Synchronization concerning the gesture
async setBoarder(value){
console.log("SETBoarder value : " + value)
this.setState({boarderstatus:value })
console.log("SETBoarder boarderstatus : " + value)
}
renderCard(item,index){
if (item.category === this.state.boarderstatus)
{
return (
<TouchableOpacity styles={style.btn}>
<Card>
<CardItem>
<Left>
<Thumbnail
source={require('../data/photo/photo_234459.jpg')}
style={{width:80,height:80}}/>
<Block left style={{top:-15, left:5}}>
<Title>{item.category}</Title>
<Subtitle>{item.date}</Subtitle>
</Block>
</Left>
<Right>
<Block>
</Block>
</Right>
</CardItem>
</Card>
</TouchableOpacity>
);
}
}
render() {
return (
...
<FlatList
data={BoardData}
keyExtractor={(item)=>item.id}
renderItem={(item, index) => this.renderCard(item, index)}
/>
);
}
}

Ok Fix :
Just instance BoardData json object to BoardData here is the code:
<FlatList data={BoardData.BoardData}
keyExtractor={(item)=>item.id}
renderItem={(item, index) => this.renderCard(item, index)}/>

Related

Print all elements of fetched data array in react

Hey I am a beginner in react trying to make my first full stack app, I am fetching data from mongodb using axios and storing data in fetchedjobs array. Jobtitle array only has the title property of the fetchedjobs and I want to print all the entries but not able to. For now I am printing these elements by hard coding the indexes {this.state.jobtitle[0]} .
Please Help
class FindJob extends Component{
constructor(props){
super(props);
this.state={
fetchedjobs:[],
jobtitle:[],
}
}
componentDidMount(){
axios.get(' http://localhost:4002/api/findjob')
.then(res=>{
this.setState({
fetchedjobs:res.data
})
let jobtitle=[]
this.state.fetchedjobs.map(fetchedjob=>
jobtitle.push(fetchedjob.jobtitle)
)
console.log(jobtitle[0])
this.setState({
jobtitle
})
})
}
render(){
return(
<div className="content">
<h5>{this.state.jobtitle[0]}</h5>
</div>
);
}
}
export default FindJob;
fetched json
[
{
"_id": "600469700459a40c088f3dde",
"jobtitle": "swe",
"company": "ibm",
"officelocation": "ggn",
"jobtype": "Part Time",
"publisher": "sid",
"date": "2021-01-17T16:44:32.084Z",
"__v": 0
},
{
"_id": "600469aa0459a40c088f3ddf",
"jobtitle": "janitor",
"company": "cisco",
"officelocation": "delhi",
"jobtype": "Full Time",
"publisher": "tanmya",
"date": "2021-01-17T16:45:30.218Z",
"__v": 0
},
{
"_id": "60046ae8b95ae81c14278f9e",
"jobtitle": "fljdk",
"company": "ndkf",
"officelocation": "mdfkfm",
"jobtype": "Part Time",
"publisher": "tanmya",
"date": "2021-01-17T16:50:48.311Z",
"__v": 0
}
]
You can create sync call in setState method and try it,
axios.get(' http://localhost:4002/api/findjob')
.then(res=>{
this.setState({ fetchedjobs:res.data }, () => {
let jobtitle=[]
this.state.fetchedjobs.map(fetchedjob=>
jobtitle.push(fetchedjob.jobtitle)
)
this.setState({ jobtitle})
})
})
Try this:
render(){
return(
<div className="content">
{this.state.jobtitle.length?this.state.jobtitle.map((item)=>{
return <h5>{item._id}</h5> //here you can display any property that you wish to
})
:null}
</div>
);
}

How can I fetch a particular data from nested array from JSON file in Angular by using params?

This is my JSON file.
{mood:
[ {
"id":"1",
"text": "Annoyed",
"cols": 1,
"rows": 2,
"color": "lightgreen",
"route":"/angry",
"musics": [
{
"id": "0",
"name": "English- Heaven's Peace",
"image": "images/music.png",
"link": "https://www.youtube.com/playlist?list=PLPfXrbtn3EgleopO8DiEdsNKgqYZZSEKF",
"descpription": "Tunes that soothe your pained soul",
"reviews": [
{
"name": "abc",
"rating": 4,
"review": "energetic",
"date": ""
}
]
},
{
"id": "1",
"name": "English- Hell's Fire",
"image": "images/music.png",
"link": "https://www.youtube.com/playlist?list=PLPfXrbtn3EgmZitRQf1X1iYwWW_nUF44L",
"descpription": "Beats that match the ones of your heart",
"reviews": [
{
"name": "abc",
"rating": 3.5,
"review": "energetic",
"date": ""
}
]
},
{
"id": "2",
"name": "Hindi",
"image": "images/music.png",
"link": "",
"descpription": "",
"reviews": [
{
"name": "abc",
"rating": 4,
"review": "energetic",
"date": ""
}
]
},
{
"id": "3",
"name": "Punjabi",
"image": "images/music.png",
"link": "https://www.youtube.com/playlist?list=PLPfXrbtn3Egnntch2thUO55YqPQgo4Qh7",
"descpription": "",
"reviews": [
{
"name": "abc",
"rating": 4,
"review": "energetic",
"date": ""
}
]
},
{
"id": "4",
"name": "Mix and Match",
"image": "images/music.png",
"link": "https://www.youtube.com/playlist?list=PLPfXrbtn3EglN5LVTETqH3ipRLfXmY6MB",
"descpription": "",
"reviews": [
{
"name": "abc",
"rating": 5,
"review": "energetic",
"date": ""
}
]
}
]
} ]
}
I have created angular services in a file name mood.services.ts
import { Injectable } from '#angular/core';
import { Mood } from '../shared/mood';
import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';
import { map, catchError } from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { baseURL } from '../shared/baseurl';
import { ProcessHTTPMsgService } from './process-httpmsg.service';
#Injectable({
providedIn: 'root'
})
export class MoodService {
constructor(private http: HttpClient,
private processHTTPMsgService: ProcessHTTPMsgService) { }
getMoods(): Observable<Mood[]> {
return this.http.get<Mood[]>(baseURL + 'moods')
.pipe(catchError(this.processHTTPMsgService.handleError));
}
getMood(id: number): Observable<Mood> {
return this.http.get<Mood>(baseURL+'moods/'+id)
.pipe(catchError(this.processHTTPMsgService.handleError));
}
getMoodIds(): Observable<number[] | any> {
return this.getMoods().pipe(map(moods => moods.map(mood => mood.id)))
.pipe(catchError(error => error));
}
getMusicIds(): Observable<number[] | any> {
return this.getMoods().pipe(map(musics => musics.map(music => music.id)))
}
}
And this is my musicdetail.component.ts file which will fetch the data of the particular music that is chosen.
import { Component, OnInit, Inject } from '#angular/core';
import { Mood } from '../shared/mood';
import { Music } from '../shared/music';
import { Review } from '../shared/review';
import { MoodService } from '../services/mood.service';
import { Params, ActivatedRoute } from '#angular/router';
import { Location } from '#angular/common';
import { switchMap } from 'rxjs/operators';
#Component({
selector: 'app-musicdetail',
templateUrl: './musicdetail.component.html',
styleUrls: ['./musicdetail.component.scss']
})
export class MusicdetailComponent implements OnInit {
mood : Mood;
music: Music;
musicIds: string;
errMess: string;
prev : string;
next : string;
review: Review;
constructor(private moodservice: MoodService,
private route: ActivatedRoute,
private location: Location,
#Inject('BaseURL') private BaseURL) { }
ngOnInit(): void {
this.route.params.pipe(switchMap((params: Params) => {return this.moodservice.getMood(params['id']);
}))
.subscribe(mood => {this.mood = mood;}, errmess => this.errMess = <any>errmess);
}
}
I have passed both mood.id and music.id when clicked in music.component.ts using '[routerLink]="['/musicdetails', mood.id, music.id]"`, on the list of music but I am unable to make logic to fetch particular music to display all its details. I am able to get mood-id using getMood(id) service but unable to do the same for music inside that mood.
WARNING:
your JSON data is wrong, Either you have missing single quote or double quote or 2nd bracket or third bracket. I don't know what you missed, its a long JSON file .
There is a JSON fixing website ( this one ) . I pasted your JSON and fixed it first.
Now I am writing this answer using correct version of your JSON (you can see it below)
So here it the answer:
The answer is simple - just use filter method to filter a particular property you need
.ts :
let jsonData =
{
"mood":[
{
"id":"1",
"text":"Annoyed",
"cols":1,
"rows":2,
"color":"lightgreen",
"route":"/angry",
"musics":[
{
"id":"0",
"name":"English- Heaven's Peace",
"image":"images/music.png",
"link":"https://www.youtube.com/playlist?list=PLPfXrbtn3EgleopO8DiEdsNKgqYZZSEKF",
"descpription":"Tunes that soothe your pained soul",
"reviews":[
{
"name":"abc",
"rating":4,
"review":"energetic",
"date":""
}
]
},
{
"id":"1",
"name":"English- Hell's Fire",
"image":"images/music.png",
"link":"https://www.youtube.com/playlist?list=PLPfXrbtn3EgmZitRQf1X1iYwWW_nUF44L",
"descpription":"Beats that match the ones of your heart",
"reviews":[
{
"name":"abc",
"rating":3.5,
"review":"energetic",
"date":""
}
]
},
{
"id":"2",
"name":"Hindi",
"image":"images/music.png",
"link":"",
"descpription":"",
"reviews":[
{
"name":"abc",
"rating":4,
"review":"energetic",
"date":""
}
]
},
{
"id":"3",
"name":"Punjabi",
"image":"images/music.png",
"link":"https://www.youtube.com/playlist?list=PLPfXrbtn3Egnntch2thUO55YqPQgo4Qh7",
"descpription":"",
"reviews":[
{
"name":"abc",
"rating":4,
"review":"energetic",
"date":""
}
]
},
{
"id":"4",
"name":"Mix and Match",
"image":"images/music.png",
"link":"https://www.youtube.com/playlist?list=PLPfXrbtn3EglN5LVTETqH3ipRLfXmY6MB",
"descpription":"",
"reviews":[
{
"name":"abc",
"rating":5,
"review":"energetic",
"date":""
}
]
}
]
}
]
} ;
// music - i can save here
let r = jsonData.mood[0].musics.filter(data => data.id == "2");
// music - or i can console.log it also
// i am comparing with 2 here - compare with your id number
// according to your need
console.log(jsonData.mood[0].musics.filter(data => data.id == "2"));
// in the same way you can search mood also
console.log(jsonData.mood.filter(data=> data.id == "1"));
to get something from parameter of url : follow this
there are multiple ways to get params from url
see this question : stackoverflow
see this blog : digitalocean

issues with fetching Json in react

I apologise as this is probably either very basic or i've done something compeltely wrong. I'm brand new to React, and coding in general, and I'm trying to make a React app that shows the recipes im using on cards. The cards in turn should be searchable and dynamic, dissapearing if they don't match etc.
This is my app.js file, that when run, it just brings up my custom "Loading" screen without data. Where have I messed up on this?
import React, {Component} from 'react';
import CardList from './CardList';
import SearchBox from './SearchBox';
import Scroll from "./Scroll";
import "./App.css"
class App extends Component {
constructor() {
super()
this.state = {
recipes: [],
searchfield: "",
}
}
componentDidMount() {
fetch("./recipedata.json")
.then(response => { return response.json();})
.then(recipedata => {this.setState({recipes: recipedata})});
}
onSearchChange= (event) =>{
this.setState({searchfield: event.target.value})
}
render() {
const filteredRecipe = this.state.recipes.filter(recipes =>{
return recipes.name.toLowerCase().includes(this.state.searchfield.toLowerCase());
})
if (this.state.recipes.length === 0) {
return <h1 class="f1 tc">Loading</h1>
} else {
return(
<div className="tc">
<h1 className="f1">Recipes</h1>
<SearchBox searchChange={this.onSearchChange} />
<Scroll>
<CardList recipe={filteredRecipe}/>
</Scroll>
</div>
)
}
}
}
export default App
Thanks in advance
edit: I have been asked to post the contents of recipedata.json:
[
{
"id" : 1,
"name" : "Carrot cake",
"type" : "sweet",
"author" : "Grandma",
"link" : "recipes/carrotcake.html"
},
{
"id" : 2,
"name" : "Spicy chicken pitta filling",
"type" : "savoury",
"author" : "Grandma",
"link" : "recipes/chickenpitta.html"
},
{
"id" : 3,
"name" : "Mushroom ham and chicken crusty puff pies",
"type" : "savoury",
"author" : "Grandma",
"link" : "recipes/crustypuff.html"
},
{
"id" : 4,
"name" : "Sweet potato pumpkin seed rolls",
"type" : "savoury",
"author" : "Grandma",
"link" : "recipes/sweetpotrolls.html"
},
{
"id": 5,
"name": "Wild mushroom wafer",
"type": "savoury",
"author" : "Grandma",
"link": "recipes/mushroomwafer.html"
},
{
"id": 6,
"name": "Piri Piri chicken sauce",
"type": "savoury",
"author": "Grandma",
"link": "recipes/piriRecipe.html"
},
{
"id": 7,
"name": "Chicken Liver Pate'",
"type": "savoury",
"author": "Grandma",
"link": "recipes/pate.html"
},
{
"id": 8,
"name": "Creamy mushroom pasta",
"type": "savoury",
"author": "Grandma",
"link": "recipes/mushroompasta.html"
},
{
"id": 9,
"name": "Cheesey garlic bread",
"type": "savoury",
"author": "Grandma",
"link": "recipes/gbread.html"
},
{
"id": 10,
"name": "Mini quiches",
"type": "savoury",
"author": "Grandma",
"link": "recipes/miniquiche.html"
},
{
"id": 11,
"name": "Sticky lemon ginger cake",
"type": "sweet",
"author": "Grandma",
"link": "recipes/stickyrecipe.html"
},
{
"id": 12,
"name": "Sticky toffee pudding",
"type": "sweet",
"author": "Grandma",
"link": "recipes/stickytoffee.html"
},
{
"id": 12,
"name": "Iced cream buns",
"type": "sweet",
"author": "Grandma",
"link": "recipes/icedcreambuns.html"
},
{
"id": 13,
"name": "Pineapple Cake",
"type": "sweet",
"author": "Grandma",
"link": "recipes/pineapplecake.html"
}
]
Edit 2:
Thanks for your help all, I've now fixed the app.js file and the Json is being returned. I'm now faced with this error in my CardList.js component:
TypeError: Cannot read property 'map' of undefined
CardList
C:/Users/mattj/OneDrive/Desktop/coding/gmcb-react-app/src/CardList.js:5
2 | import Card from './Card.js';
3 |
4 | const CardList = ({recipes}) => {
> 5 | return <div>
6 | {recipes.map((recipedata, i) => {
7 | return(
8 | <Card
code:
import React from 'react';
import Card from './Card.js';
const CardList = ({recipes}) => {
return <div>
{recipes.map((recipedata, i) => {
return(
<Card
key={i}
id={recipes[i].id}
name={recipes[i].name} />
)
})}
</div>
}
export default CardList
What have I messed up here?
Regarding issue #2 you posted it is really tough to say, however I think you are overcomplicating things with your card list. You should simply pass an array of filtered recipes to your component.
Your card list component you should just pass an entire recipe option to the component instead of trying to pass specific props. If in the future you add more keys to each recipe object you wont have to adjust your card list
const CardList = ({recipes}) => {
return (
<div>
{
recipes.map(recipe => {
return <Card recipe={recipe} key={recipe.id} />
})
}
</div>
)
}
Inside your card component you can destructure the keys off the recipe object
const Card = ({recipe}) => {
return (
<div>
<h3>{recipe.name}</h3>
<p>{recipe.type} - {recipe.author}</p>
<hr />
</div>
)
}
I made you a code sandbox, I used React Hooks and a mockAxios call in order to fake what a server would do and so you have some code for if you want to call an API in the future.
https://codesandbox.io/s/broken-glitter-4wb61?file=/src/App.js
You don't need to use fetch to get the data from the local json file.
You can simply import the contents of ./recipedata.json by doing this:
import recipedata from './recipedata.json';
And then change your componentDidMount to this:
componentDidMount() {
this.setState({ recipes: recipedata });
}
You mostly use fetch when you are trying to fetch data from a http server. Read more here and here
To support #Qubaish Bhatti's comment, yes, there is no need to have recipes in state. You can use it directly and do away with this.state.recipes

How to get local images dynamically from .json file in React-native

I have json file named "Bread.json" following is the content of the file.
How to use image name dynamically in <Image>
I'm trying following but getting error. I'm getting image name's array from json file into the Flatlist, so {item.img} = my image name from json file. But not working!
<Image source={require('../images/'+{item.img})} />
So, how can I use image name in source of the <Image>, Also I can not use require() function into my json file. Any help?
"bread.json"
[
{
"id": "1",
"img": "1.jpg",
"cat": "Breakfast",
"title": "Small Semolina Griddle Breads"
},
{
"id": "2",
"img": "2.jpg",
"cat": "Side",
"title": "Corn Bread"
},
{
"id": "3",
"img": "3.jpg",
"cat": "Appetizer",
"title": "Fresh Tomato Bruschetta"
}
]
You can try this!
<Image source={getImageSource(item.img)} />
function getImageSource(image) {
let imageSrc = require('../images/logo.png');
switch (image) {
case "1.jpg":
imageSrc = require('../images/1.jpg');
break;
default:
break;
}
return imageSrc;
}
Hope this helps!
1) Create a file (to hold JSON data) e.g bread.js:
const Breads=[
{
"id": "1",
"img" : require('../images/1.jpg'),
"cat": "Breakfast",
"title": "Small Semolina Griddle Breads"
},
{
"id": "2",
"img" : require('../images/2.jpg'),
"cat": "Side",
"title": "Corn Bread"
},
{
"id": "3",
"img" : require('../images/3.jpg'),
"cat": "Appetizer",
"title": "Fresh Tomato Bruschetta"
}
]
export default Breads;
2) Then import the data in component and loop through the list using a FlatList
import Breads from './bread.js';
<FlatList
data={Breads}
keyExtractor={(item, index) => item.id}
renderItem={({item}) => <View>
<Image source={item.src} />
<Text>{item.title}</Text>
</View>
}
/>

Creating new component for each Artist in a Music App (Similar to iTunes, Spotify, ect) -- Angular4

So I am creating a music app clone of the Google All Access music web app using Angular 4.
So far, here is the data service I am using for the JSON data of all the artists, albums, ect (haven't filled it out yet with the correct data entirely lol):
import { Injectable } from '#angular/core';
#Injectable()
export class DataService {
constructor() { }
data = {
"artists": [
{
"artistName": "Lupe Fiasco",
"artistsPicture": "../assets/artists-images/lupe.jpg",
"genre": "Hip-Hop",
"albums": [
{ "name": "Food & Liquor",
"artistName": "Lupe Fiasco",
"isExplicit": "true",
"albumCover": "../assets/album-covers/f&l.jpg",
"songs": {
"name": "Kick, Push",
"file": "mp3"
},
},
{ "name": "The Cool",
"artistName": "Lupe Fiasco",
"isExplicit": "true",
"albumCover": "../assets/album-covers/thecool.jpeg",
"songs": {
"name": "Kick, Push",
"file": "mp3"
},
}
]
},
{
"artistName": "Flume",
"artistsPicture": "../assets/artists-images/flume.jpg",
"genre": "Electronic",
"albums": [
{ "name": "Flume",
"artistName": "Flume",
"isExplicit": "true",
"albumCover": "../assets/album-covers/flume.jpg",
"songs": {
"name": "Sleepless",
"file": "mp3"
}
},
{ "name": "Skin",
"artistName": "Flume",
"isExplicit": "true",
"albumCover": "../assets/album-covers/skin.png",
"songs": {
"name": "Sleepless",
"file": "mp3"
}
}
]
},
{
"artistName": "Linkin Park",
"artistsPicture": "../assets/artists-images/linkinpark.jpg",
"genre": "Nu-Metal",
"albums": [
{ "name": "Hybrid Theory",
"artistName": "Linkin Park",
"isExplicit": "true",
"albumCover": "../assets/album-covers/meteora.jpg",
"songs": [{"name": "Sleepless","file": "mp3"}]
}
]
},
{
"artistName": "Drake",
"artistsPicture": "../assets/artists-images/drake.jpg",
"genre": "Hip-Hop",
"albums": [
{ "name": "Views",
"artistName": "Drake",
"isExplicit": "true",
"albumCover": "../assets/album-covers/views.png",
"songs": {
"name": "Sleepless",
"file": "mp3"
}
}
]
},
{
"artistName": "J.Cole",
"artistsPicture": "../assets/artists-images/jcole.jpg",
"genre": "",
"albums": [
{ "name": "2014 Forest Hills Drive",
"artistName": "J.Cole",
"isExplicit": "true",
"albumCover": "../assets/album-covers/fhd.jpg",
"songs": {
"name": "Sleepless",
"file": "mp3"
}
}
]
},
{
"artistName": "Eminem",
"artistsPicture": "../assets/artists-images/eminem.jpg",
"genre": "Hip-Hop",
"albums": [
{ "name": "Marshal Matthers LP",
"artistName": "Eminem",
"isExplicit": "true",
"albumCover": "../assets/album-covers/mmlp.jpg",
"songs": {
"name": "Sleepless",
"file": "mp3"
}
}
]
},
]
}
}
So here is what I am having a problem with. In the ARTIST section, the User would obviously be clicking on an artist to go to that specific artist page, where I would be displaying all the artists' albums, top songs, info, ect.
In my head I am like, oh man, I would have to create a new component for each artist? darth vader voice NNNoooOOOOOOoooOOoooOOO!!! With only 6 artists, It wouldn't be a problem. But when I am thinking about scalability.. that has to suck!
So is there any type of solution of routing to a component that has the info of the artist that is clicked?
Here is the AlbumsComponent in my app for what it is worth:
HTML:
<div class="card" *ngFor='let x of getAlbums'>
<img src="{{x.albumCover}}" alt="">
<div class="info">
<p class="album-name">{{ x.name }}</p>
<p class="artist-name">{{ x.artistName }}</p>
</div>
</div>
ComponentTS:
import { Component, OnInit } from '#angular/core';
import { DataService } from './../../data.service';
#Component({
selector: 'app-albums',
templateUrl: './albums.component.html',
styleUrls: ['./albums.component.css']
})
export class AlbumsComponent implements OnInit {
constructor(private dataService: DataService) { }
artistData = this.dataService.data.artists;
albums: any[] = [];
getAlbums = this.artistData.reduce(
(acc: any, next: any) => {
next.albums.forEach(album => {
acc.push(album);
});
return acc;
}, []);
ngOnInit() {
console.log(this.getAlbums);
}
}
Intuitively, I am thinking of maybe making a ArtistPageComponent, then somehow getting data to that component depending on that Artist.
Any help to at least put me in the right direction would help!
In your app.module.ts as a new route as
RouterModule.forRoot([
........,
{path: 'artists/:artistId', component: ArtistPageComponent }
])
artists-page.component.ts
export class ArtistPageComponent implements onInit{
artistId:string;
constructor(private route: ActivatedRoute){
}
ngOnInit(){
this.artistId = this.route.snapshot.params['artistId'];
}
}
Now you can add a route to http://app-domain/artists/123 and this will navigate you to artist component with id.