0

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.

  • just create a model class, subscribe/parse ur json to model and save everything in a model array –  Sep 08 '20 at 02:28
  • @Frost Can u show me how I can get musicID from params? – Aayush Jain Sep 08 '20 at 08:12
  • check my answer below, I compared with music id 2 `let r = jsonData.mood[0].musics.filter(data => data.id == "2");` –  Sep 08 '20 at 08:19

1 Answers1

1

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

enter image description here

there are multiple ways to get params from url

  1. see this question : stackoverflow
  2. see this blog : digitalocean
  • https://www.typescriptlang.org/play is good place to try different outputs. My code worked there. –  Sep 08 '20 at 04:04
  • I might have missed the quotes here, but Its working in my application. I need to know the way to create a function in services so that I can get musicID of a particular music from params. Forexample- `localhost:4200/musicdetails/1/2` where 1 is moodID and 2 is musicID. I am able to get moodID from params as shown in `musicdetail.component.ts` file but unable to do the same for musicID @Frost – Aayush Jain Sep 08 '20 at 08:19
  • @AayushJain i am a bit confused, lets say `x()` is a function your output is musicid, what is your input of the function? // particular music from params // please explain what your param is - i mean what should be function input –  Sep 08 '20 at 08:22
  • @AayushJain oh i get it sorry, –  Sep 08 '20 at 08:25
  • `getMusic(moodId: number, musicId: number): Observable { return this.getMood(moodId).pipe(map(mood => mood.musics.find(music => music.id == musicId)), // please note: not === since id is a string in your json, but a number param ); }` I have this function in my services. I don't know if it will work but how can use it to get musicID from params just like I got moodID from param as I have implemented in `musicdetail.component.ts` file – Aayush Jain Sep 08 '20 at 08:27
  • click the image for better quality –  Sep 08 '20 at 08:32
  • Okay. Thanks.I look into it and get beck to you – Aayush Jain Sep 08 '20 at 09:23