【问题标题】:Accesing individual properties of an Object inside subscribe function in angular以角度访问订阅函数内部对象的各个属性
【发布时间】:2020-10-22 16:56:20
【问题描述】:

我有一个工作 api,它在查询时返回一组表实体对象。这是我的 Angular 应用程序中对应的 tableEntity

export interface TableEntity {
    partitionKey: string;
    rowKey: string;
    ownerid: string;
    filetype: string;
    companyName: string;
    parentID: string;
    isdirectory: boolean;
    filesize: Int32Array;
}

在我的 Angular 应用程序中,我使用服务查询此 api,这是联系 api 并将表实体对象发送到组件的相关代码

getFileStructureData(){
   return this.http.get(this.baseUrl + 'list').pipe(
     map((user: TableEntity) => {
       return user;
     })
   )

现在在组件内部我可以访问这个对象,当我控制台记录这个对象时,它会按预期返回对象数组。

this.TableService.getFileStructureData().subscribe(response => {
    console.log(response);
    }, error => {
                console.log(error);
                })

但是当我尝试通过控制台记录对象的各个属性时,

this.TableService.getFileStructureData().subscribe(response => {
    console.log(response.companyName);
    }, error => {
                console.log(error);
                })

我在控制台日志中得到未定义的值。如何访问订阅函数中 tableEntity 对象的各个属性?非常感谢您的帮助

【问题讨论】:

  • 你确定你没有得到实体数组吗?
  • “它按预期返回对象数组”。 map((user: TableEntity) => { 会不正确,它需要是 map((users: TableEntity[]) => { 或类似的权利?就像在一组用户中一样。此外,该地图也没有做任何事情,您可以简单地return this.http.get< TableEntity[]>(this.baseUrl + 'list')
  • 数组没有.companyName 属性。如果你想打印出它的一个属性,你可以试试response.length。如果您想要响应数组中第一个TableEntitycompanyName,您可以尝试console.log(response[0].companyName)

标签: angular rxjs pipe observable subscribe


【解决方案1】:

首先,你不需要pipe()getFileStructureData里面,你可以这样做:

getFileStructureData(){
   return this.http.get(this.baseUrl + 'list')
)

而您的响应可能是对象数组,请尝试以下操作:

this.TableService.getFileStructureData().subscribe(response => {
    console.log(response[0].companyName);
    }, error => {console.log(error);})

【讨论】:

    猜你喜欢
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多