【问题标题】:How to Iterate Observable response object from component in Angular 2如何从Angular 2中的组件迭代Observable响应对象
【发布时间】:2017-01-04 00:57:37
【问题描述】:

我从 Component 类调用服务并获取 Observable (Customers) Object 作为响应。 如果我使用 <div *ngFor="let cust of customerDetailsItem"> {{cust.id}} </div> 然后我得到了值。但如果我想在组件中使用可观察到的响应,那么它会显示“Undefined”。

    constructor(public service:ViewListCustomerServiceService) {
    this.service.getCustomerItemList().subscribe(lst =>this.customerDetailsItem=(lst));
console.log(this.customerDetailsItem);    //Showing Undefined.
  }

因为我想要“customerDetailsItem”将数据分配给组件类中的Json 对象。

【问题讨论】:

    标签: angular


    【解决方案1】:

    您的对象this.customerDetailsItem 将是未定义的,直到您收到订阅的响应。因此,您可以做的是在收到lst 后执行必要的代码。

    constructor(...) {
        this.service.getCustomerItemList()
            .subscribe(lst=>this.initialize(lst));
    }
    
    initialize(lst: any) {
       this.customerDetailsItem = lst;
       // from now on your object will be set
    }
    

    【讨论】:

    • 非常感谢。它为我工作,
    • 您好,先生,实际上我正在使用“ng2-smart-table”。如果我通过执行上述解决方案发送,我想将“customerDetailsItem”作为表数据(到@Input 源)传递,那么表也显示为空。如果我手动传递数据,那么只有它的显示。例如:data:CustomerDetailsItem[]=[ { id:1, "name":"Customer 1", "details":"Customer 1", "active":false }, { "id":2, "name": "Customer 2", "details":"Customer 2 details go here", "active":false } ]
    • 尝试在 smart-table 元素上使用 *ngIf="customerDetailsItem",否则如果没有更大的代码示例,我真的不知道
    • 先生,我认为正如您在第一个答案中所说,智能表组件在服务响应之前加载,所以 @Input 数据;是由“未定义”注入的。如果是这样,那么请建议我如何停止加载“智能表”组件,直到我们得到服务响应
    • 如前所述,将 *ngIf 添加到元素 <ng2-smart-table *ngIf="customerDetailsItem" [settings]="settings" [source]="customerDetailsItem"></ng2-smart-table>
    猜你喜欢
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    相关资源
    最近更新 更多