-1

I have simple Angular 2 app as below:

Data structure

class Item {
  name: string,
  status: boolean
}

Template

<ul *ngIf="items">
  <li *ngFor="let item of items">{{ item.name }}</li>
</ul>

Component

export class ItemsComponent implement OnInit {

  items: Item[]

  constructor(private itemService: ItemService) { }

  ngOnInit() {
    this.getItems();
  }

  private getItems(): void {
    this.itemService.getItems().then(items => this.items = items);
  }

}

with asynchronous data receiver getItems() of ItemService which uses Promise.

This app works great. The full item list is shown on the browser.


I want to display only the items with status true. To do this, I implemented a simple pipe to filter items by status:

@Pipe({
  name: 'filterByStatus'
})
export class FilterByStatusPipe implements PipeTransform {

  transform(votes: Vote[], status: boolean): Vote[] {
    return votes.filter(vote => vote.status === status);
  }
}

and I updated li tag in my template as

<li *ngFor="let item of items|filterByStatus:true">{{ item.name }}</li>

But, this update makes <ul *ngIf="items"> false so <li>s are not computed. (i.e. items === undefined)

I don't know why first version works well but updated version does not. And how can I get items with status === true?

Thanks.

Analysis
  • 230
  • 1
  • 8
  • http://stackoverflow.com/questions/38057537/how-to-check-length-of-the-an-observable-array/38057574#38057574 – yurzui Feb 14 '17 at 15:33
  • 2
    your code is actually correct and should work as is. How sure are you that `vote.status` is actually filled with a boolean? It also makes no sense that a pipe makes `items` be undefined. Something else is wrong there – Poul Kruijt Feb 14 '17 at 15:35

1 Answers1

0

Everybody should know:

DON'T use status for the name of your properties or variables. It would be potentially used in your environment.

See this: JS reserved keywords list


Renaming solves the problem.

Analysis
  • 230
  • 1
  • 8