【发布时间】: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