angular - Angular 9:如何获取从 rest api 服务调用返回的对象的属性
问题描述
我正在使用 Angular 9 编写一个应用程序,而且我是新手。我已经编写了一个服务 API 来获取数据,但是我无法理解如何从我的服务调用中获取数据到 Angular 组件中。
这是endcustomer.ts中的示例对象:
export interface IEndCustomer {
endCustomerId: number;
endCustomerName: string;
fein: string;
这是我在endcustomer.service.ts中调用我的 REST API 的地方:
import { Injectable } from '@angular/core'
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { IEndCustomer } from './endcustomer';
import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
export class EndCustomerService {
private APIurl2 = "https://localhost:44331/api/endcustomer/GetEndCustomerById";
constructor(private http: HttpClient) { }
getEndCustomerById(id) {
return this.http.get<IEndCustomer>(this.APIurl2 + "/" + id);
}
这就是我尝试在endcustomer_detail.component.ts中使用一个最终客户的详细信息创建表单的地方:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { IEndCustomer } from './endcustomer';
import { EndCustomerService } from './endcustomer.service';
@Component({
selector: 'endcustomer',
templateUrl: './endcustomer_detail.component.html'
})
export class EndCustomerDetailComponent implements OnInit {
pageTitle: string = 'Customer Detail'
customer: IEndCustomer;
constructor(private endcustomerService: EndCustomerService) { }
ngOnInit() {
let id = +this.route.snapshot.paramMap.get('id');
this.endcustomerService.getEndCustomerById(id).subscribe({
next: customer => {
this.customer.endCustomerId = customer.endCustomerId;
this.customer.endCustomerName = customer.endCustomerName;
this.customer.fein = customer.fein;
}
}
问题是我收到一条错误消息,“在类型‘未知’上不存在属性‘endCustomerId’,属性下方有一条波浪状的红线:this.customer.endCustomerId = customer.endCustomerId 。我不明白为什么客户是列为“未知”。
如果我尝试“ this.customer.endCustomerId = customer;”,则错误显示为“类型‘未知’不可分配给类型‘数字’。
如果我尝试“ this.customer = customer;” 然后错误显示“类型'{}'缺少类型'IEndCustomer'中的以下属性:endCustomerId,endCustomerName,fein”
我尝试了许多不同的方法,因为 Internet 上的示例的组织方式似乎都有些不同,但我就是不明白。有人可以解释我做错了什么吗?是否有更好的方法来获取返回对象的属性,以便我可以拥有一个 endCustomer,然后我可以在 html 页面上使用它来显示 ID 和名称?
解决方案
如果编译代码会发生什么?它可以编译没有任何错误。据我了解,这些可能是 TS Lint 错误。
如果您想删除波浪形的红线,请尝试以下操作
服务
getEndCustomerById(id): Observable<IEndCustomer> { // <-- mention return type
return this.http.get<IEndCustomer>(this.APIurl2 + "/" + id);
}
零件
ngOnInit() {
let id = +this.route.snapshot.paramMap.get('id');
this.endcustomerService.getEndCustomerById(id).subscribe(
customer => { this.customer = customer },
error => { // always good practice to handle HTTP errors }
);
}
推荐阅读
- python - Convert dict to HTML table
- angular - 使用原理图生成的 mat-table 时设置过滤
- python - 你如何在氢气中使用 pdb?
- javascript - 内容安全策略阻止 javascript 表单提交到 php 服务器
- javascript - 收到错误消息 TypeError:无法在以前工作的系统上调用 null 的方法“getSheetByName”
- python - 将 csv 持久化的浮点数列表读回浮点数列表
- r - 在 R 中将 yaml 文件打印为 pdf
- android - 在应用程序“onPause”Xamarin 时运行后台任务
- objective-c - Objective-C 从数学计算中得到 0
- angular - Angular 4 使用 Web Speech API