Having trouble with my Angular subscription - not behaving as I anticipated

I am facing an issue on my shop page where I have a FilterBarComponent as a child component. On initialization, I want it to emit all the categories so that all products are rendered by default. However, on my HomePageComponent, there is a button that allows users to navigate to the shopPage and view a specific category, for example, a "view shirts" button. The problem arises because the default categories array update occurs after the subscriber function finishes, and the event emitter does not fire in the subscriber. This relates to another question of mine which you can find here: Angular EventEmitter is not emitting in subscriber

FilterBarComponent


categories = [];
@Output() filteredCategory = new EventEmitter<any>();
@Output() maxiumPriceEmitter = new EventEmitter<any>();
categorySub: Subscription;

formatLabel(value: number) {
    return 'R' + value;
}

constructor(private shopService: ShopService) {}

ngOnInit() {
    this.initCategories();
    this.filterCategories();
    this.updateCategories();
}

filterCategories() {
    this.shopService.filterCategories.subscribe(
        (fCategory: string) => {
            this.categories.map(category => {
                category.checked = category.name === fCategory;
            });
            this.updateCategories();
        }
    );
}

initCategories() {
    this.categories = [
        { name: 'dress', checked: true, displayName: 'Dresses' },
        { name: 'top', checked: true, displayName: 'Shirts' },
        { name: 'skirt', checked: true, displayName: 'Skirts/Pants' },
        { name: 'purse', checked: true, displayName: 'Purse' },
        { name: 'bag', checked: true, displayName: 'Bags' },
    ];
}

updateCategories() {
    const categories = this.categories
      .filter((category) => {
        return category.checked;
      });
    console.log(categories);
    this.filteredCategory.emit(categories);
}

In the console, initially I get the correct result, but then the categories array resets.

[{}] 
{name: "top", checked: true, displayName: "Shirts"}

[{…}, {…}, {…}, {…}, {…}] 
{name: "dress", checked: true, displayName: "Dresses"}
1: {name: "top", checked: true, displayName: "Shirts"}
2: {name: "skirt", checked: true, displayName: "Skirts/Pants"}
3: {name: "purse", checked: true, displayName: "Purse"}
4: {name: "bag", checked: true, displayName: "Bags"}
length: 5 

The Observable in ShopService

filterCategories = new BehaviorSubject("category");

Answer №1

I want to give credit to @Józef Podlecki for his helpful response to another one of my questions.

After considering his advice, I've realized that using a BehaviorSubject instead of a regular subject in the ShopService will be more beneficial.

filterCategories = new BehaviorSubject("all");

Incorporating this change into the Filter Bar Component:


  ngOnInit() {
    this.initCategories();
    this.filterCategories();
  }

  filterCategories() {
    this.shopService.filterCategories.subscribe((fCategory: string) => {
      if (fCategory === 'all') {
        this.updateCategories();
      } else {
        this.categories.map((category) => {
          category.checked = category.name === fCategory;
        });
        this.updateCategories();
      }
    });
  }

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

The functionality of Angular 2 md-radio buttons in reactive forms seems to be hindering the display of md-inputs

Currently, I am following the instructions for implementing reactive form radio buttons on a project using Angular 2.1.2 and Google's MD-alpha.10 Atom-typescript shows no errors in my code. However, when testing the application, I encountered the foll ...

Setting up a basic webhook server with Node and Express

I'm struggling to locate comprehensive tutorials on webhooks for beginners. Being new to this concept, I have only come across basic explanations of how they operate. Our current requirement is to inform users of our APIs about new records. With Kafk ...

Managing Asynchronous Operations in Vuex

Attempting to utilize Vue's Async Actions for an API call is causing a delay in data retrieval. When the action is called, the method proceeds without waiting for the data to return, resulting in undefined values for this.lapNumber on the initial call ...

The function 'downloadFunc' is not recognized as a valid function within the context of ReactJS custom hooks

Here is a unique custom hook that triggers when the user presses a button, calling an endpoint to download files as a .zip: import { useQuery } from 'react-query'; import { basePath } from '../../config/basePath'; async function downlo ...

What is the method for writing the following line in CSHTML server-side code?

<script> function a(id) { var table = document.getElementById(id); .... } </script> @{ //Is there a way to rewrite the line "var table = document.getElementById(id)" here within the ser ...

How can I resolve the "web page not found" error when using jQuery .replace()?

Working on HTML and javascript/jquery scripts, I have encountered a peculiar issue. My script utilizes a for-in loop to iterate through a JavaScript object, substituting specific patterns in HTML-formatted lines with data from the object using jQuery .appe ...

Automatically submit form in Javascript upon detecting a specific string in textarea

Just getting started with JS and I have a question that's been bugging me. I have a simple form set up like this: <form method="POST" action="foo.php"> <textarea name="inputBox123"></textarea> <input type="submit" value="Go" name ...

Troubleshooting problems with Window.postMessage()

When attempting to fetch data from different domains, I am facing an issue. However, if I run the code on the same server, everything works perfectly fine and I am able to retrieve the message. index.html: <head> <title>Test 1</title&g ...

The name field in the request body is currently undefined

Currently, I am working on developing a basic blog page using technologies such as ejs, JavaScript, Node.js, Express, and body-parser. While working on passing inputs to the command line, specifically for the title, I encountered an issue. When I used req ...

If two requests are made at the same time, they will both yield identical results

Encountering an issue where running two separate HttpClient requests to my Spring Boot backend yields the same result for both requests (the first request's result). This occurs approximately 30% of the time: //request 1 with url_1= "http://local ...

Upcoming Authentication Update: Enhancing User Profile with Additional Data Points

I recently encountered an issue with my typescript application that uses Next Auth v4 along with GithubProvider and MongoDBAdapter. I needed to add a new field called role to the User schema. Researching online, most solutions suggested adding a function ...

Console displays 'undefined' when using the post method with Node.js/Express

Below is the code for my upload.ejs page: <%- include('header' ,{ title:"Playground" }) -%> <div class="wrapper"> <form action="/upload" method="POST" enctype="multipart/form-data"> <input type="text" name="name" place ...

Pass a parameter to an AJAX request in order to retrieve data from a JSON file that is limited to a specific

I am working with a JSON file named example.json, structured as follows: { "User1": [{ "Age":21, "Dogs":5, "Cats":0 }], "User2": [{ "Age":19, "Dogs":2, "Cats":1 }] "User3 ...

AngularJS is not responding to a 400 bad request

Despite my efforts to find solutions on Google and Stack Overflow for similar or identical issues, as a newcomer, none of them have provided me with any insight on how to resolve the issues in my code. Here is the script I am working with: $http.post(&ap ...

Encountering a JavaScript error in the backend of Joomla 3.2

I am facing an issue with buttons on my Joomla 3.2.3 sites in the backend. The save, edit (material, module, menu...) buttons are not working properly. These sites were deployed using Akeeba Kickstart. Interestingly, everything worked fine on the developme ...

When encountering an "uncaught SyntaxError" in the $.parseJSON function, one may want to investigate

When using this jQuery function, I encounter an Uncaught SyntaxError: Unexpected token u error if the cookie $.cookie('chk_ar') is undefined. function checkBgNoise() { // checks background noise option state, // activates 'on' click i ...

How to Properly Implement app.use() in Express for Middleware

What is the reason behind some middleware functions being passed in with invocation parentheses, while an anonymous function is passed in without being invoked? app.use(logger()); app.use(bodyParser()); If logger() is evaluated immediately and the return ...

How can I load a function from the HTML file that is being loaded using .load() in jQuery?

Within my main window main.html, there is a div button that, when clicked, loads another html file into a large div. This is achieved using the .load() function: $('#mainpanel').load("search.htm"); The "search.htm" file contains a function cal ...

Combining tuples with their corresponding data types

Trying to define a new type: type Union = [1, "one"] | [1, "first"] | [2, "two"] type GetTuple<T, U> = Extract<T, [U, ...unknown[]]>; type ObjectFromUnion<T extends Union[0] = Union[0]> = { number: T, word: ?? } Looking to utiliz ...

Enclose each set of objects, such as text, within a separate div, except for div elements

Is there a way to wrap each immediate group of objects that are not contained in a div with a wrap class? Input: var $code = 'Lorem Ipsum <p>Foo Bar</p> <div class="myclass"></div> <p>Foo Bar</p> <div clas ...