KeysPipe类在调用时返回对象的两倍

时间:2017-01-10 11:37:38

标签: angular ngfor

我有一个问题,就是通过调用service.ts方法正确显示检索到的对象的值。实际上,对象显示两次,我不知道为什么。

我的KeysPipe类为我提供了一个空对象,然后是我需要的完整对象 那是我的代码:

@Component({
    selector: 'app-api',
    template: `<h1>{{api}}</h1>
                  <br />
                  <table class="table">
                  <tr>
                      <th>Name</th>
                      <th>Street</th>
                      <th>House number</th>
                      <th>Postal code</th>
                      <th>City</th>
                      <th>Country</th>
                      <th>number</th>
                  </tr>
                  <tr>                              
                    <td *ngFor="let key of customers | keys ;">
                         {{ key.value }}
                    </td>
                  </tr>
                  </table>
                      `,
    providers: [
        CustomerService
    ]
})

export class CustomerComponent implements OnInit
{
    api: string;
    public customers: Customer[];

    constructor(private customerService: CustomerService)
    {
        this.api = "API Customers";
    }

    ngOnInit()
    {

        this.customerService.getCustomer(3804).subscribe(result => this.customers = result);
    }
}

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform
{
    transform(value)
    {
        let keys = [];
        for (let key in value)
        {
            keys.push({value: value[key]});
        }
        console.log(keys);
        return keys;
    }
}

[I have one empty object and then the object I need !! ][1]
[1]: https://i.stack.imgur.com/xMTZt.png

1 个答案:

答案 0 :(得分:0)

首次执行管道,当Angular运行更改检测时。仅在调用第一个更改检测方法ngOnInit之后。这意味着在组件从服务获取数据之前,KeysPipe会运行。

你应该向KeysPipe添加条件,返回空数组或null,如果参数将为null,f.e。:

transform(value: any) {
    let keys = [];
    if(value) {
        for (let key in value) {
            //some code
        }
    }
    return keys;
}