Using the pipe feature in Angular 2, we can easily filter an object

I have a

query:

export class Task {
    public id: number;
    public title: string;
    public isDone: boolean;
    public createdDate: Date;
    public assignedTo: string;
}

A method:

fetchTasks(): Observable < Task[] > {
    return this.http.get(this.tasksUrl)
        .map(this.extractData)
        .catch(this.handleError);
}

private extractData(res: Response) {
    let body = res.json();
    return body || {};
}

In my view:

fetchTasks(){
    this.taskService.fetchTasks()
      .subscribe(
        tasks => this.tasks = tasks,
        error => this.errorMessage = <any>error
      );
}

And template file:

<div class="ui large selection animated divided list">
    <a *ngFor="let task of (tasks | taskFilter:false)" class="item">
        <div class="right floated content">
            <div class="ui vertical animated negative button" tabindex="0">
                <div class="hidden content">Delete</div>
                <div class="visible content">
                    <i class="fa fa-trash" aria-hidden="true"></i>
                </div>
            </div>
        </div>
        <i class="minus square outline icon"></i>
        <div class="content">
            <div class="header">{{task.title}}</div>
            <div class="description">{{task.createdDate | date:"MMM-dd-yyyy"}}</div>
        </div>
    </a>
</div>

The issue arises when I attempt to utilize the pipe to filter the completed tasks, resulting in an error stating Cannot read property filter of undefined.

Have I made a mistake or are there alternative methods to filter it without using a pipe?

The pipe I created:

transform(allTasks: Task[], args?: boolean){
    if (allTasks === null) {
      return null;
    }
    return allTasks.filter(task => task.isDone);
}

Your assistance is greatly appreciated.

Answer №1

Consider updating the if (allTodos === null) statement to simply if (!allTodos). It seems like the issue lies in reaching the .filter method before your this.todos array is populated, as you're only verifying that it's not null.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular-material: What is the best way to align an md-button in between multiple blocks?

How can I position the md-button component like the image below? Reference Image I have attempted to do this without success. I searched through the Angular Material docs, but couldn't find any relevant information. Here is my Plunker: Plunker Link ...

The application's functionality does not support the return type of `express-session

this.app.use( session({ // session configuration }) ); Encountering an error when passing the session configuration as shown above: Argument of type 'RequestHandler<ParamsDictionary, any, any, any>' is not assignabl ...

Storing JSON data in a variable using .subscribe is not possible in Angular

Currently, I am encountering an issue where I cannot successfully store the specific data obtained from a Post request into a variable. How can I resolve this and ensure that only the desired data is stored? After making a Post request and receiving back ...

The challenge of validating in Typescript and utilizing type inference

I am currently facing an issue with a function that resembles the one provided below (I have created a simplified example for discussion purposes): interface Variable { someMethod: () => void } const validateVariable(variable: Variable | undefined) { ...

delivering nicely presented string with AngularJS {{ }}

I need help formatting a string using AngularJS in HTML with curly brackets. Here is an example in the HTML code: <center> {{italicsPlease()}} </center> And here is the corresponding method in AngularJS: $scope.italicsPlease = function() { ...

Does Vetur have additional undefined types in the type inference of deconstructed props?

When reviewing the code below, Vetur concluded that x,y are of type number | undefined. The presence of undefined is leading to numerous warnings when using x,y further in the code. Is there a way to eliminate the undefined from the type inference? <s ...

The issue of Angular2 routing not working with an empty route has been

My routing setup is structured as follows: In the app module, I have defined the initial level of routing using the following configuration: const routes: Routes = [ { path: 'login', component: LoginComponent, }, { path: 'dash', red ...

Utilizing Dynamic IDs within an AngularJS Template

Incorporating a jQuery plugin within an AngularJS directive is the task at hand. The directive is intended to be called like this: <my-dialog data-trigger-id="myTriggerId">My dialog content...</my-dialog> Within the directive template, it app ...

What is the relationship between an odd number and the value 1 in JavaScript that results in a 'true' outcome?

I encountered a straightforward problem, but the solution has left me perplexed. function transformArray(numbers) { // If 'i' is an odd number, i & 1 will evaluate to 1 or true return numbers.map(i => (i & 1) ? i * 3 : i * 2); } co ...

Issue with TypeScript when using destructuring on an object

When attempting to destructure data from an object, I encountered the error message Property XXXX does not exist on type unknown. This issue arose while using React Router to retrieve data. let {decoded, reasonTypes, submissionDetails} = useRouteLoaderDa ...

What is the best way to handle special characters in an Angular date pipe?

In my Angular project, I have a date variable called today. I am currently using the date pipe on it in this format: {{today | date:'LLLL d'}} February 13 However, I want to display it differently as follows: 13 days so far in February Unf ...

Ways to give preference to custom css instead of the default Angular-material css

The search label is originally padded to the left by Angular-material.min.css with a value of padding-left: 3px. https://i.sstatic.net/YQpAb.png My attempt to customize the padding to the right in my custom.less file has not overridden the default CSS fr ...

Angular continually monitors changes for dom-to-image and generates countless renders

I am trying to implement a feature in my Angular 4 application where child-components render wallpapers for themselves using dom-to-image-more. The issue arises when I try to dynamically render these child-components using *ngFor. The parent component h ...

What is the best way to iterate through an array of objects in Angular 2 and retrieve a specific key from each object?

I am working with an array of objects where I need to iterate over the array, access a specific key in each object, and check if the string property matches any words from another array. If there is a match, I want to perform a certain action. While I can ...

Error message for invalid form control not displayed when value is assigned to form control in Angular

I am currently working with this editor: <div id="editor"></div> which sets its value to a form control. this.FrmGroup.get("name").setValue(this.quill.root.innerHTML)` <div *ngIf="FrmGroup.get('name').inv ...

Adjusting ES2015 Map to accommodate the expected functionality

Exploring the capabilities of ES2015 Maps has been quite exciting, as I'm starting to see its potential. However, I've encountered a use case that has me stumped on whether Maps can handle it. Let's take a look at my class: class A { ...

Angular2 - Leveraging data to dynamically control radio buttons

I am looking to implement radio buttons in a form using Angular 2 with a data-driven approach. In my component, I have set up a form as follows: import { Component } from '@angular/core'; import {FormControl, FormGroup, Validators} from '@a ...

Switching to a different ion-tab in Ionic causes the history to be lost

While transitioning between pages with the ion-tabs directive, Ionic seems to forget the history. Can you provide a solution for this issue or identify the specific section of code that may be causing it? ...

Creating dynamic ng-models with AngularJS for input types of text is a useful feature to have in your

Currently, I am working on a scenario that involves nesting repetition as shown below: <form name="task_form" ng-app="myApp" ng-submit="tasksubmit()"> <ul class="items-list"> <li ng-repeat="task in taskslist | orderBy:orderProp"& ...

Maintaining accurate type-hinting with Typescript's external modules

Before I ask my question, I want to mention that I am utilizing Intellij IDEA. In reference to this inquiry: How do you prevent naming conflicts when external typescript modules do not have a module name? Imagine I have two Rectangle classes in different ...