从HTTPGET返回一个自定义对象列表,以便在Angular 2应用程序中使用

Return a List of custom objects from an HTTP GET for use in an Angular 2 app

本文关键字:Angular 应用程序 列表 返回 HTTPGET 对象 自定义 一个      更新时间:2023-09-26

我正试图找出如何正确返回自定义对象列表并使用HTML文件打印其内容。

以下是HTTPGET方法的样子(为了简单起见,我只简化了一些内容来说明问题):

[HttpGet("/atr/testing")]
public List<CustomObject> GetCustomObjects()
{
    //MasterObject.CustomObjects returns a List of CustomObjects
    return MasterObject.CustomObjects();
}

我的TypeScript文件(称为home.ts)订阅并调用HttpGet方法-home类如下(我已经排除了所有导入和@Component部分):

export class Home {
public selectedConfiguration: string = 'TESTVALUE';
constructor(private http: Http) {
    this.getConfigurations()
        .subscribe(res => {
            this.selectedConfiguration = res;
        });
}
getConfigurations() {
    console.log('Home:getConfigurations entered...');
    return this.http.get('atr/testing')
        .map((response) => {
            console.log(response);
            return response.json();
        });
}

}

正如您所看到的,构造函数调用"getConfigurations",它调用HttpGet方法。让我困惑的是,我该如何正确使用返回的响应?根据我的理解,响应以JSON字符串的形式返回(这就是为什么Home类中的selectedConfiguration变量是字符串值而不是List)。当我试图在HTML文件中用{{selectedConfiguration}}打印出"selectedConfiguration"字符串时,我得到的是:

[object Object],[object Object],[object Object],[object Object]

如果我在HTML中使用{{selectedConfiguration[0]}},我只得到一个:〔object object〕

GET方法返回的List中应该有4个CustomObject,而JSON响应似乎至少有这个。每个CustomObject都有"Name"、"Date"、"Time"等变量。我曾尝试使用{{selectedConfiguration[0].Name}}在HTML中打印数据,但它什么也不打印。我真的不确定从这里做什么(或者我是否做错了什么)来显示每个对象的信息。

简短答案

在您的示例中,您试图将JSON对象转换为字符串。为了让它发挥作用,你可能必须做:

this.selectedConfiguration = JSON.stringify(res);

答案很长

假设您的CustomObject类看起来像:

public class CustomObject
{
    public string Name { get; set; }
    public DateTime Date { get; set; }
}

在Angular代码中,创建一个模仿它的接口。在开发工具中验证大小写是否匹配("Name"而不是"Name"):

export interface ICustomObject {
    Name: string;
    Date: Date;
}

利用TypeScript的类型检查,将返回的列表实际读取为CustomObjects:的数组

export class Home implements OnInit {
  public configurations: ICustomObject[];
  public selectedConfiguration: ICustomObject;
  constructor(private http: Http) {
    // move initialization code to ngOnInit. Don't forget the import and implements
  }
  ngOnInit() {
    this.getConfigurations()
        .subscribe((customList: ICustomObject[]) => {
            this.configurations = customList;
            // todo: determine the selected configuration
            this.selectedConfiguration = this.configurations[0];
        });
  }
  getConfigurations(): ICustomObject[] {
    return this.http.get('atr/testing')
        .map((response: Response) => {
            return <ICustomObject[]>response.json();
        });
}

将其作为json结果返回:

[HttpGet("/atr/testing")]
public JsonResult GetCustomObjects()
{
    //MasterObject.CustomObjects returns a List of CustomObjects
    return Json(MasterObject.CustomObjects());
}