无法使用 Angular 服务从 Angular 应用程序中的 JSON 文件访问数据

Posted

技术标签:

【中文标题】无法使用 Angular 服务从 Angular 应用程序中的 JSON 文件访问数据【英文标题】:Unable to access data from JSON file in Angular application using Angular services 【发布时间】:2020-12-26 00:17:22 【问题描述】:

这是我的 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,但无法为那种情绪中的音乐做同样的事情。

【问题讨论】:

【参考方案1】:

你是这个意思吗?

getMusic(moodId: number, musicId: number): Observable<Music> 
  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
  );

【讨论】:

谢谢@MoxxiManagarm,看来这就是我需要的。我稍后会尝试与您联系。但是如何在我的 musicdetails.component.ts 文件中使用它?由于musicid也在参数中。例如:localhost:3000/dishdetails/1/2 其中“1”是moodID,2 是musicID。从params获取moodID的逻辑,我已经实现了。 当然,只需从路由中获取两个参数并将其传递给服务 好的,我会尽力让它发挥作用,如果我需要进一步的帮助,我会回复你。非常感谢。干杯。 我在musicdetail.component.ts 中使用了此代码:this.route.params.pipe(switchMap((params: Params) =&gt; return this.moodservice.getMusic(params['id'], params['id']); )) .subscribe(music =&gt; this.music = music;, errmess =&gt; this.errMess = &lt;any&gt;errmess); 您提供的服务有效,但每次我选择音乐时,它都会更改moodID 而不是musicID。我的意思是当我选择音乐时,moodID 正在改变,但 musicID 是固定的。我猜这些参数没有从上面的代码中正确获取。

以上是关于无法使用 Angular 服务从 Angular 应用程序中的 JSON 文件访问数据的主要内容,如果未能解决你的问题,请参考以下文章

无法从 websocket rxjs 节点 Angular 获得响应

无法使用 Angular 7 将授权标头发送到节点 11/Express 4 服务器

我无法在 Angular 中获得 REST 服务响应

无法使用 Observable、Firebase (Angular 6) 为 var 赋值

Angular:为组件字段提供对服务功能的引用并从模板调用它无法按预期工作

Apollo Angular 无法从 GraphQL/MongoDB 获取数据