KeysPipe class return 对象调用时的两倍

KeysPipe class return two times the object when called

我在正确显示通过调用 service.ts 方法检索到的对象的值时遇到了一些问题。实际上,该对象显示了两次,我不知道为什么。

我的 KeysPipe class 给我一个空对象,然后给我我需要的完整对象 那是我的代码:

@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

第一次,管道被执行,当Angular 运行变化检测。只有在调用第一个变化检测方法 ngOnInit 之后。这意味着 KeysPipe 运行,在组件将从服务获取数据之前。

您应该向 KeysPipe 添加条件,即 return 空数组或 null,如果参数将为 null,f.e.:

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