【问题标题】:How can I fetch a particular data from nested array from JSON file in Angular by using params?如何使用参数从 Angular 中的 JSON 文件中的嵌套数组中获取特定数据?
【发布时间】:2020-12-26 04:23:57
【问题描述】:

这是我的 JSON 文件。

{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": ""
           }            
       ]     
  }
]
}  ]
}

我在文件名 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)))
}
}

这是我的 musicdetail.component.ts 文件,它将获取所选音乐的数据。

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);
}

}

当我在 music.component.ts 中使用 '[routerLink]="['/musicdetails', mood.id, music.id]"` 在列表中单击时,我已经通过了 mood.id 和 music.id音乐,但我无法制定逻辑来获取特定音乐以显示其所有细节。我可以使用 getMood(id) 服务获取mood-id,但无法为那种情绪中的音乐做同样的事情。

【问题讨论】:

  • 只需创建一个模型类,订阅/解析你的 json 模型并将所有内容保存在模型数组中
  • @Frost 你能告诉我如何从参数中获取 musicID 吗?
  • 在下面查看我的答案,我对比了音乐 id 2 let r = jsonData.mood[0].musics.filter(data =&gt; data.id == "2");

标签: json angular angular-services angular-components


【解决方案1】:

警告:

您的JSON 数据错误,您缺少单引号或双引号或第二个括号或第三个括号。我不知道你错过了什么,这是一个很长的JSON 文件。

有一个JSON 修复网站(this one)。我粘贴了你的JSON 并先修复了它。

现在我正在使用您的JSON 的正确版本写这个答案(您可以在下面看到)

这就是答案:

答案很简单 - 只需使用过滤器方法来过滤您需要的特定属性

.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"));

从 url 的参数中获取一些东西:按照这个

有多种方法可以从 url 获取参数

  1. 看到这个问题:stackoverflow
  2. 看到这个博客:digitalocean

【讨论】:

  • typescriptlang.org/play 是尝试不同输出的好地方。我的代码在那里工作。
  • 我可能错过了这里的引号,但它在我的应用程序中工作。我需要知道在服务中创建函数的方法,以便我可以从参数中获取特定音乐的音乐 ID。例如-localhost:4200/musicdetails/1/2,其中 1 是 moodID,2 是 musicID。我可以从参数中获取moodID,如musicdetail.component.ts 文件中所示,但无法对musicID @Frost 执行相同操作
  • @AayushJain 我有点困惑,可以说x() 是一个函数,你的输出是musicid,你输入的函数是什么? // 来自参数的特定音乐 // 请解释你的参数是什么 - 我的意思是应该是函数输入
  • @AayushJain 哦,对不起,
  • getMusic(moodId: number, musicId: number): Observable&lt;Music&gt; { return this.getMood(moodId).pipe(map(mood =&gt; mood.musics.find(music =&gt; music.id == musicId)), // please note: not === since id is a string in your json, but a number param ); } 我的服务中有这个功能。我不知道它是否会起作用,但是如何使用它从参数中获取音乐 ID,就像我在 musicdetail.component.ts 文件中实现的那样从参数中获取moodID
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-24
  • 1970-01-01
  • 1970-01-01
  • 2019-09-10
相关资源
最近更新 更多