如何将JSON数据传递到Angular的数组

发布于 2025-01-30 17:17:06 字数 1135 浏览 3 评论 0原文

我想将我从API获得的JSON数据传递到数组中,并在模板中显示该信息,但我不知道该怎么做。

此错误在我的控制台上示意:

”在此处输入图像说明”

我的TS文件:

this.api.getJoursFeries(year).subscribe(
      (data: feries[]) => {
        this.joursFeries = data;
        // console.log(data);
      }, (error: HttpErrorResponse) => {
        console.log(error);
      }
)

我的服务文件:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { feries } from '../models/feries';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  private apiBaseUrl = 'https://calendrier.api.gouv.fr/jours-feries/metropole'

  constructor(private http: HttpClient) { }

  getJoursFeries(annee : number): Observable<feries[]> {
    return this.http.get<feries[]>(`${this.apiBaseUrl}/${annee}.json`);
  }
}

I want to pass json data that I get from an API into an array and display that information in my template and I don't know how to do that.

this error apears on my console :

enter image description here

my ts file :

this.api.getJoursFeries(year).subscribe(
      (data: feries[]) => {
        this.joursFeries = data;
        // console.log(data);
      }, (error: HttpErrorResponse) => {
        console.log(error);
      }
)

my service file :

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { feries } from '../models/feries';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  private apiBaseUrl = 'https://calendrier.api.gouv.fr/jours-feries/metropole'

  constructor(private http: HttpClient) { }

  getJoursFeries(annee : number): Observable<feries[]> {
    return this.http.get<feries[]>(`${this.apiBaseUrl}/${annee}.json`);
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

明月夜 2025-02-06 17:17:06

假设您已经定义了一个表示响应中给出的对象的接口,则有两种方法可以在模板中表示该数据。

最简单的方法是从订阅中分配从组件到数组响应的数组变量,然后在模板中使用 *ngfor Directive显示数据的

   //ts file
import { Component } from '@angular/core';
import {ApiService} from 'path/to/service'
import {Feries} from 'path/to/feriesModel'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'myClass';

  joursFeries: Feries[] = []

  constructor(private apiService: ApiService) {
  }

  ngOnInit() {
    apiService.getJoursFeries().subscribe(data => {
      this.joursFeries = data;
    })

  }
}

//html file

<div *ngFor="let ferie of joursFeries">
    <p>{{ferie.name}}</p>
  </div>

更有原则性的方法是在您的服务中创建一个extiviourSubject,然后将其转换为转换通过.asobservable()可观察到
将此服务分配到可观察到的组件中的可观察变量。但是,这需要对RXJS库的一些了解以及如何与可观察到的适当合作。
让我知道您是否需要解决方案的更多详细信息

Assuming that you have already defined an interface that represents the objects given from the response, you have two ways to represent that data in the template.

The easiest way is to assign an array variable from the component to the array response from the subscription and then in the template you would use *ngFor directive to display the data

   //ts file
import { Component } from '@angular/core';
import {ApiService} from 'path/to/service'
import {Feries} from 'path/to/feriesModel'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'myClass';

  joursFeries: Feries[] = []

  constructor(private apiService: ApiService) {
  }

  ngOnInit() {
    apiService.getJoursFeries().subscribe(data => {
      this.joursFeries = data;
    })

  }
}

//html file

<div *ngFor="let ferie of joursFeries">
    <p>{{ferie.name}}</p>
  </div>

A more principled way would be to create a BehaviourSubject in your service then convert it to an Observable via .asObservable()
Assign this service Observable to an Observable variable in your component.ts file and then use the ngFor with the observable with the async pipe. However this requieres some knowledge of the RxJS library and how to properly work with Observables.
Let me know if you need further details for the solution

清眉祭 2025-02-06 17:17:06

https://calendrier.api.api.gouv.fr/ JORS-FERIES/METROPOLE/2021.JSON 不是数组,而是具有不同键值对的JavaScript对象。

{
     "2021-01-01": "1er janvier",
     "2021-04-05": "Lundi de Pâques",
     "2021-05-01": "1er mai",
     "2021-05-08": "8 mai",
     "2021-05-13": "Ascension",
     "2021-05-24": "Lundi de Pentecôte",
     "2021-07-14": "14 juillet",
     "2021-08-15": "Assomption",
     "2021-11-01": "Toussaint",
     "2021-11-11": "11 novembre",
     "2021-12-25": "Jour de Noël" 
}

在您的服务中,您需要将JSON对象(从服务器)映射到数组(您可以与 *ngfor一起使用)。

假设Feries被定义为:

type feries = {
  fDate: string;
  fName: string;
};

然后在您的服务中您可以更改将数据输入的代码:

getJoursFeries(annee: number): Observable<feries[]> {
    return this.http.get<any>(`${this.apiBaseUrl}/${annee}.json`).pipe(
      map((val) => {
        let feriesList: feries[] = [];
        for (var key of Object.keys(val)) {
          feriesList.push({ fDate: key, fName: val[key] });
        }
        return feriesList;
      })
    );
  }

您可以共享Feries类型吗?然后,我可以正确更新答案。

The JSON response from https://calendrier.api.gouv.fr/jours-feries/metropole/2021.json is not an Array but a Javascript Object with different Key-Value pairs.

{
     "2021-01-01": "1er janvier",
     "2021-04-05": "Lundi de Pâques",
     "2021-05-01": "1er mai",
     "2021-05-08": "8 mai",
     "2021-05-13": "Ascension",
     "2021-05-24": "Lundi de Pentecôte",
     "2021-07-14": "14 juillet",
     "2021-08-15": "Assomption",
     "2021-11-01": "Toussaint",
     "2021-11-11": "11 novembre",
     "2021-12-25": "Jour de Noël" 
}

In your service you need to map the JSON object (from the server) to an Array (that you can use with *ngFor).

Let's assume the feries are defined as:

type feries = {
  fDate: string;
  fName: string;
};

then in your service you can change the code for getting the data into:

getJoursFeries(annee: number): Observable<feries[]> {
    return this.http.get<any>(`${this.apiBaseUrl}/${annee}.json`).pipe(
      map((val) => {
        let feriesList: feries[] = [];
        for (var key of Object.keys(val)) {
          feriesList.push({ fDate: key, fName: val[key] });
        }
        return feriesList;
      })
    );
  }

Can you share the feries type? Then I can update the answer properly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文