Automatically showcasing filtered arrays in the Angular view through efficient sorting mechanisms

I have successfully managed to post and retrieve data from a database. However, I am facing an issue where the view only updates the value upon refreshing. It seems like the filter method is creating a new array, so I am puzzled as to why it's not showing automatically.

Check out the stackblitz example: https://stackblitz.com/edit/angular-6ni1pg

Below is the component code:

export class TransactionsComponent implements OnInit {
  transactions: Transaction[];
  groceriesList: Transaction[]; 
  transList: Transaction[];

  constructor(private postsService: PostService) {}



  ngOnInit() {
      this.postsService.fetchPosts().subscribe(posts => {
      this.transactions=posts; 
      this.groceriesList=posts.filter(item => item.category==="Groceries")
      this.transList=posts.filter(item => item.category==="Transportation")

    });
    // this.refreshGroceries()   
    }

And here is the HTML structure:


<div class="row">
  <div class="col-xs-10">

    <ul class="list-group">
      <a 
      class="list-group-item" 
      style="cursor:pointer"
      *ngFor="let transaction of transactions">
    {{ transaction.name }} ({{ transaction.amount }}) - ({{ transaction.category }})</a>
    </ul>
  </div>
</div>

<div class="row">
  <div class="col-xs-10">
    <h1>Groceries</h1>
    <ul class="list-group">
      <a 
      class="list-group-item" 
      style="cursor:pointer"
      *ngFor="let grocery of groceriesList">
    {{ grocery.name }} ({{ grocery.amount }}) - ({{ grocery.category }})</a>
    </ul>
  </div>
</div>

<div class="row">
  <div class="col-xs-10">
    <h1>Transportation</h1>
    <ul class="list-group">
      <a 
      class="list-group-item" 
      style="cursor:pointer"
      *ngFor="let item of transList">
    {{ item.name }} ({{ item.amount }}) - ({{ item.category }})</a>
    </ul>
  </div>
</div>

Answer №1

this.postsService.fetchPosts().subscribe(...)
is designed to run only once, without continuous polling of the API. Therefore, in onCreatePost, you must either re-call
this.postsService.fetchPosts().subscribe
or append the result of
this.postsService.createAndStorePost
to the arrays.

Refreshing after posting

ngOnInit() {
  this.loadPosts();
}

onCreatePost(postData: Transaction) {
  this.postsService.createAndStorePost(postData.name, postData.amount, postData.category)
    .subscribe(() => this.loadPosts());
}

loadPosts() {
  this.postsService.fetchPosts().subscribe(posts => {
    this.transactions=posts; 
    this.groceriesList=posts.filter(item => item.category==="Groceries");
    this.transList=posts.filter(item => item.category==="Transportation");
  });
}

Lastly, make changes to createAndStore in post.service.ts

createAndStorePost(name: string, amount: number, category: string) {
  const postData: Transaction = {name: name, amount: amount,  category: category}
  return this.http
    .post<{name: string }>(
      'https://budget-dfc78.firebaseio.com/posts.json',
      postData
    );
}

Appending post results to arrays

onCreatePost(postData: Transaction) {
  this.postsService.createAndStorePost(postData.name, postData.amount, postData.category)
    .subscribe(transaction {
      this.transactions.push(transaction);

      if (transaction.category==="Groceries") {
        this.groceriesList.push(transaction);
      }

      if (transaction.category==="Transportation") {
        this.transList.push(transaction);
      }
    });
}

Answer №2

Modify the ngOnInit function as shown below

ngOnInit() {
    this.postsService.fetchPosts().subscribe(posts => {
        this.transactions = posts; 
      },
      () => {},
      () => {
        this.groceriesList = this.transactions.filter(item => item.category === "Groceries")
        this.transList = this.transactions.filter(item => item.category === "Transportation")
      }
    );
}

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

Adjust the component suppliers based on the @input

If I were to implement a material datepicker with a selection strategy, I would refer to this example There are instances where the selection strategy should not be used. The challenge lies in setting the selection strategy conditionally when it is insta ...

The implementation of async await within a switch case statement is failing to function properly

Is it possible to wait for the resolution of a promise within a switch case statement by using the keyword await? I am facing an issue with my Angular component where the following code is causing crashes in my application. switch (this.status) { ...

Using Typescript to import Eslint with the `import/named` method

My project utilizes Eslint with the following configurations: parser: @typescript-eslint/parser 1.4.2 plugin: @typescript-eslint/eslint-plugin 1.4.2 resolver: eslint-import-resolver-typescript 1.1.1 rule extends: airbnb-base and plugin:@typescript-eslint ...

Building a hybrid application in Angular using UpgradeModule to manage controllers

I am currently in the process of upgrading a large AngularJS application using UpgradeModule to enable running AngularJS and Angular 6 simultaneously without going through the preparation phase, which typically involves following the AngularJS style guide. ...

Ways to obtain the present value in Angular

Hello, I am looking for assistance in displaying Toast notifications on my View whenever the number of notifications increases (i.e., when new data is added to the database). I have attempted to use this function, but I am unsure how to retrieve the curre ...

Directive does not support the new animations in Angular 2 RC 4

It appears that in the current release, we are only able to add animations to components and cannot define them as directives. For example: The following code works: @Component({ selector: "animate-demo", animations: [ trigger('openC ...

Tap into the live monitoring feature of angular-cli build

Is there a way to integrate custom functionality with angular-cli's build/watch command? ng build /w This command creates files and places them in the project's /dist folder I am looking to automatically copy the contents of the dist folder ...

Encountered issue in Angular: Object prototype must be either an Object or null, not undefined

I encountered an issue with my Angular application when trying to install npm dependencies using npm i. I kept receiving a "sha1 seems to be corrupted" error. To resolve this, I deleted the package-lock.json file and was able to successfully install all th ...

The Bootstrap modal backdrop is now displaying prominently in front of the modal following the latest Chrome update

Chrome version: Version 111.0.5563.64 (Official Build) (x86_64) Bootstrap: 4.3.1 Recently, there has been an issue with the modal backdrop appearing in front of the modal itself after a Chrome update. The problem does not seem to be related to z-index, an ...

Create the accurate data format rather than a combination in GraphQL code generation

In the process of migrating a setup that mirrors all the types exactly as on the server to one based solely on the document nodes we've written. Currently, the configuration is in .graphqlrc.js /** @type {import('graphql-config').IGraphQLCo ...

I am having trouble getting Angular 6 to work with lowdb

I am currently in the process of developing an Electron app with Angular 6, utilizing lowdb as a local database. This is all very new to me and I am learning through trial and error. However, I seem to be encountering difficulty resolving the following er ...

"Error message: ngrx router is unable to access the property 'firstChild' as it is undefined

i'm encountering an issue with ngrx's router-store /module @NgModule({ imports: [ .... StoreModule.forRoot(reducers) StoreRouterConnectingModule.forRoot(), ... ], .... }) /store import { getSelectors, ...

What is the best way to bring a module into an Angular project?

I have a project in Angular with an additional module created as an npm package. The structure of the module is as follows: --otherModule --other-module.module.ts --index.ts --package.json index.ts: export { OtherModule } from './other-module ...

Utilizing the Solana Wallet Key for ArweaveJS Transaction Signing

Is there a method to import a Solana wallet keypair into the JWKInterface according to the node_modules/arweave/node/lib/wallet.d.ts, and then generate an Arweave transaction using await arweave.createTransaction({ data }, jwk);? Metaplex utilizes an API ...

Having issues with the ASP.NET Web Api and Angular Frontend integration

I recently tried following a guide on ASP.NET Web Api and Angular, which you can find here. While I followed the steps closely, the only difference was that I used .NET version 7 instead of version 6 for the Web Api. When I ran the project for the first ti ...

Implementing TypeScript/Angular client generation using Swagger/OpenAPI in the build pipeline

Generating Java/Spring Server-Stubs with swagger-codegen-maven-plugin In my Spring Boot Java project, I utilize the swagger-codegen-maven-plugin to automatically generate the server stubs for Spring MVC controller interfaces from my Swagger 2.0 api.yml fi ...

Using the length of an array as an iterator within a nested ngFor loop in Angular 9

I am looping through an array of objects where each object contains another array of objects with attributes like "name" and "id". The length of this array of objects (noticias) varies. I am struggling to display these values and have only managed to acce ...

What steps should I take to fix the SyntaxError occurring with the unexpected token 'export' in a React Next.js project?

Currently working on a React Next.js project and I've come across an unexpected SyntaxError: Unexpected token 'export' issue. I've reviewed the solutions provided here, but I'm having trouble grasping how to correctly implement th ...

Angular2: Promise Rejection: Quotes cannot be used for evaluation in this component

I'm currently working on a component in Angular that includes an input parameter: import {Component, Input} from '@angular/core'; @Component({ selector: 'comment', template: ` <div class="col-lg-6 col-md-6 ...

Tips for handling promises in a class getter method in TypeScript

In two of my classes, I use async/await functions to retrieve products from the product class. export default class Products { async getProducts() : Promise<[]> { return await import('../data/products.json'); } } export defa ...