【问题标题】:Angular 13 use RxJS to get array of objectsAngular 13 使用 RxJS 获取对象数组
【发布时间】:2022-01-16 18:16:51
【问题描述】:

我正在尝试使用 Angular 前端和 rxjs 从 REST API 获取并显示 JSON 对象数组。

以下是我的服务:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { LicenseFoodBusiness } from './license-food-business';

import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';



@Injectable({
  providedIn: 'root'
})
export class LicenseFoodBusinessService {
  private REST_API_SERVER = "http://localhost:8080/foodlicenses";
  
  constructor(private httpClient: HttpClient) { }
  
  public sendGetRequest(): Observable<LicenseFoodBusiness[]> {
    return this.httpClient.get<LicenseFoodBusiness[]>(this.REST_API_SERVER);            
    }
}

以下是我的组件代码:

import { Component, OnInit } from '@angular/core';;
import { LicenseFoodBusinessService } from '../license-food-business.service';
import { LicenseFoodBusiness } from '../license-food-business';

import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';

@Component({
  selector: 'app-license-food-business',
  templateUrl: './license-food-business.component.html',
  styleUrls: ['./license-food-business.component.css']
})
export class LicenseFoodBusinessComponent implements OnInit {

  
  results: LicenseFoodBusiness[] = [];
  
  constructor(private lfbs: LicenseFoodBusinessService) { }
    
  ngOnInit(): void {
    this.lfbs.sendGetRequest()
        .subscribe(data => this.results = data);
      
    }
  }

以下是我的模型:

export interface LicenseFoodBusiness {
    LicenseId: number;
    SECP: string;
    NTN: string;
    SRB: string;
    SalesTax: string;
    NumberOfWarehouses: number;

}

以下是我的组件 html 中的 sn-p:

<tr *ngFor="let licensefoodbusiness of results | async" >
        <td> {{licensefoodbusiness.LicenseId}} </td>
....

我收到以下错误:

请帮忙。

更新:

按照建议的编辑后,它确实编译了,但现在我在 html 表中没有得到任何数据:

更新 2 使用console.log,我得到了三个从后端传递的json对象,如下所示,但是没有与数据一起显示的对象被分配给this.results。

  ngOnInit(): void {
    this.lfbs.sendGetRequest()
        //.subscribe(data => this.results = data);
        .subscribe(data => console.log(data));
      
    
  }

【问题讨论】:

  • 有点像你得到空值或反序列化不起作用。至少有3行。尝试在订阅中使用 console.log 以查看内容。
  • console.log(data) 显示 3 个 json 对象

标签: angular typescript rxjs


【解决方案1】:

您通过.subscribe“解包”来自可观察对象的值。

我认为您可以简单地删除模板中的 | async 管道。

【讨论】:

  • 删除异步后它确实编译了,但现在绑定的 html 表不包含任何数据
  • (仅供参考:这通常是一个新问题)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 2017-03-08
  • 2022-01-15
  • 2021-09-14
  • 1970-01-01
  • 2023-03-17
  • 2019-12-24
相关资源
最近更新 更多