代码之家  ›  专栏  ›  技术社区  ›  Amber Akkermans

Angular http.get()返回带有数据的数组

  •  0
  • Amber Akkermans  · 技术社区  · 1 年前

    我有一项服务:

    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs';
    import { Color } from '../model/color';
    import { HttpClient } from '@angular/common/http';
    
    @Injectable({
      providedIn: 'root'
    })
    export class ColorService {
      private productsUrl = 'http://localhost:5500/colors/';
    
      constructor(private http: HttpClient) { }
    
      getColors(): Observable<Color[]> {
        var colors = this.http.get<Color[]>(this.productsUrl + "all");
        
        return colors;
      }
    }
    

    以及获得该方法的结果的组件:

    ngOnInit(): void {
        this.colorsService.getColors()
            .subscribe((colors) => {
              this.colors = Object.values(colors);
              this.colors.sort((a,b) => a.name.localeCompare(b.name));
              console.log(colors);
            }, err => {
              this.displaySpinner = false;
            }, () => {
              this.displaySpinner = false;
            });
      }
    

    我的Color界面如下所示:

    export interface Color {
        id: number;
        number: string;
        name: string;
        imagePath: string;
        category: string;
        color: string;
        brand: string;
    }
    

    现在,当我在组件中执行此控制台日志时,它会给我一个名为colors的数组,并将另一个具有实际数据的数组作为子数组:

    {
      colors: [
        {
          id: 1,
          number: 159,
          name: 'glamorous peach',
          imagePath: '/src/assets/img/colors/color104.jpeg',
          category: 'summer',
          color: 'orange',
          brand: 'Pink Gellac'
        }
      ]
    }
    

    我似乎记得以前版本的angular不是这样的,当我在html页面中做下面这样的事情时,它无法获得color.name,我想是因为这里发生了数组嵌套:

    <mat-grid-tile *ngFor="let color of colors">
                <mat-card class="example-card"
                    style="width: 95%; border-radius:15px; box-shadow: 4px 4px 6px -1px rgba(0,0,0,0.15);">
                    <mat-card-content>
                        <mat-grid-list cols="1" rowHeight="250">
                            <mat-grid-tile class="tile" style="overflow:auto;">
                              <div class="wrapper">
                                <p>{{color.name}}</p>
                              </div>
                            </mat-grid-tile>
                          </mat-grid-list>
                    </mat-card-content>
                </mat-card>
            </mat-grid-tile>
    

    你知道如何解决这个问题吗?由于在服务中键入(Color[]),我似乎无法将此数组操作为ngFor工作所需的值。。

    3 回复  |  直到 1 年前
        1
  •  1
  •   Naren Murali    1 年前

    该结构来自API,您只需要对其进行不同的设置即可使其工作!访问颜色数组并将其设置为变量!

    ngOnInit(): void {
        this.colorsService.getColors()
            .subscribe((response: any) => {
              console.log(response);
              this.colors = <Array<Color>>response.colors;
              this.colors.sort((a,b) => a.name.localeCompare(b.name));
            }, err => {
              this.displaySpinner = false;
            }, () => {
              this.displaySpinner = false;
            });
      }
    
        2
  •  1
  •   Kareem Adel    1 年前

    在将颜色数组分配给this.colors之前,可以修改组件代码以从响应中提取颜色数组。

    ngOnInit(): void {
      this.colorsService.getColors()
        .subscribe((response) => {
          // Extract the colors array from the response
          const colorsArray = response.colors;
    
          // Sort and assign the colors array to this.colors
          this.colors = colorsArray.sort((a, b) => a.name.localeCompare(b.name));
    
          console.log(this.colors);
        }, err => {
          this.displaySpinner = false;
        }, () => {
          this.displaySpinner = false;
        });
    }
    
    
    <!--  HTML template, you can iterate over this.colors directly: -->
    <mat-grid-tile *ngFor="let color of colors">
      <mat-card class="example-card" style="width: 95%; border-radius:15px; box-shadow: 4px 4px 6px -1px rgba(0,0,0,0.15);">
        <mat-card-content>
          <mat-grid-list cols="1" rowHeight="250">
            <mat-grid-tile class="tile" style="overflow:auto;">
              <div class="wrapper">
                <p>{{color.name}}</p>
              </div>
            </mat-grid-tile>
          </mat-grid-list>
        </mat-card-content>
      </mat-card>
    </mat-grid-tile>
    
        3
  •  0
  •   Yong Shun    1 年前

    或者,您可以转换Observable值以检索 colors 阵列通过 map RxJS operator .

    import { map, Observable } from 'rxjs';
    
    
    @Injectable({
      providedIn: 'root',
    })
    export class ColorService {
      ...
    
      getColors(): Observable<Color[]> {
        return this.http
          .get<any>(this.productsUrl + 'all')
          .pipe(map((resp: any) => resp.colors as Color[]));
      }
    }
    

    Demo @ StackBlitz