Function that returns the client name using the . filter method

Asked

Viewed 40 times

1

In my template I have an interpolation that performs a call to function getNomeCliente, passing the ClienteId as a parameter:

<ng-template kendoGridCellTemplate let-dataItem>
  <div class="whole-cell">
    {{ getNomeCliente(dataItem.ClienteId) }}
  </div>
</ng-template>

I need to search the client name in my array clienteList and return only the customer name.

I tried something like:

  public getNomeCliente(clienteId: string): string{
    this.clienteList.filter((item) => {item.ClienteId.indexOf(clienteId) !== -1}).map((cliente) => { return cliente.ClienteNome});
  }

but I get in visual studio:

A Function Whose declared type is neither 'void' nor 'any' must Return a value.

  • 3

    We’re missing a return there, no?

1 answer

2


As you can see by the error, the problem is that getNomeCliente is not void, nor returns anything (any), so something needs to be returned, in this case a string. Other than that, you can use the find, instead of filter and map. Following example:

public getNomeCliente(clienteId: string): string{
    return this.clienteList.find((item) => {item.ClienteId.indexOf(clienteId) !== -1}).ClienteNome;
}

If the item.ClienteId not being an array, the best comparison would be to directly compare the Ids:

public getNomeCliente(clienteId: string): string{
    return this.clienteList.find((item) => (item.ClienteId === clienteId)).ClienteNome;
}

Below is an example of the use of find with complex object array:

const arr = [{a: 1, b:'errado'}, {a:2 , b:'certo'}];
console.log(arr.find(element => (element.a === 2)).b);

  • 1

    find comparing the ids worked perfectly for the expected purpose.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.