The variable 'selectedvalue' is being accessed before it has been initialized

I'm currently working on sharing the date between components using BehaviorSubject, but I'm encountering an error in the process.

public data = new BehaviorSubject<any>(this.selectedValue);
public sharedData = this.data.asObservable();
selectedValue: Meal[] = [];

fetchSubCategoriesFood(name: string): Observable<{ meals: Meal[] }> {
  return this.http
    .get<{ meals: Meal[] }>(
      this.recipes.listOfSubcategories + 'filter.php?i=' + name
    )
    .pipe(
      tap((result) => {
        this.selectedValue = result?.meals;
      })
    );
}

Here's how I am subscribing to the service in another component:

This is my secondary Component where I am listening for changes.

export class CategoryPageComponent implements OnInit {
  constructor(public categoryService: HomepageService) {}

  ngOnInit(): void {
    const subscription = this.categoryService.sharedData.subscribe((data) =>
      console.log(data)
    );
  }
}

Answer №1

You are only assigning selectedvalue once to a BehaviourSubject. Any subsequent updates made to selectedValue will not reflect in the BehaviourSubject.

To make sure changes are reflected, use the .next() method to update the BehaviourSubject value.

public content = new BehaviorSubject<Meal[]>([]);
public share = this.content.asObservable();

loadSubCategoriesFood(name: string): Observable<{ meals: Meal[] }> {
  return this.http
    .get<{ meals: Meal[] }>(
      this.recipies.listofsubcategories + 'filter.php?i=' + name
    )
    .pipe(
      tap((resultcategory) => {
        this.content.next(resultcategory?.meals)
      })
    );
  }
}

If you follow this approach, you can eliminate the need for selectedvalue.

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

Guide on accessing mobile information and sim card details with Ionic 3 and Cordova on Android devices

Just started using Ionic and I'm looking for guidance on how to retrieve mobile and sim details with Ionic 3 and Cordova for Android. Any help is greatly appreciated in advance! ...

The create document feature seems to be malfunctioning for some reason. Any ideas why it's not working properly in Firebase with Angular

I've been attempting to submit user data to the Firebase Firestore database, but I'm experiencing issues with the function that is supposed to create a new collection. Despite trying different methods, none of them seem to be working for me. I ha ...

Protractor experiencing difficulty in adjusting price slider

As a newcomer to protractor, I am attempting to test a price slider that sorts products based on the provided price range. Unfortunately, I am facing difficulty in dragging the slider (min point) using protractor. Can anyone provide guidance on how to move ...

Issues arising with code splitting using React HashRouter in a project utilizing Typescript, React 17, and Webpack 5

Encountered build issues while setting up a new project with additional dependencies. package.json: { "name": "my-files", "version": "1.0.0", "description": "App", "main": " ...

I want to know the most effective way to showcase particular information on a separate page using Angular

Recently, I've been working with a mock json file that contains a list of products to be displayed on a Product page. My goal is to select a specific product, such as 'Product 1', and have only that product's information displayed on th ...

Is using instanceof the most effective method to verify type in Angular?

When working with the model, we import Type1 and Type2. Using the TypeComp variable which is a union of Type1 and Type2. import { Type1, Type2 } from '.'; export type TypeComp = Type1 | Type2; In the some.component.ts file, the selectedData$ obs ...

What is the method for creating an object type that necessitates a key determined by a variable?

Is it feasible to create a custom type in TypeScript that can check if a given key exists within the Type definition? I am specifically using noUncheckedIndexAccess: true configuration. interface one { foo: string; bar: string; } interface two { b ...

Error message: Custom binding handler failed: 'Flatpickr' is not a valid constructor

Trying my hand at creating a custom binding handler in knockout for Flatpickr has hit a snag. Upon attempting to use it, an error is thrown: Uncaught TypeError: Unable to process binding "datetimepicker: function (){return startDate }" Message: Flatpickr ...

Is there a way to ensure a consistent return value when using exhaustive switch-case statements?

I'm facing an issue with the following code snippet: function (flavors: IceCreamFlavor): 'like'|'dislike' { switch (flavors) { case IceCreamFlavor.vanilla: return 'dislike'; case IceCreamFl ...

Are there any solutions to refresh a page by clicking a button in next.js?

I am currently learning how to work with next.js and I'm facing an issue where I need to reload my page to make a new API request. As a beginner, I'm not sure how to achieve this. I've tried a few methods but none of them seem to work. Below ...

How can I retrieve the value of a promise in Promise.map?

I am currently working on a project that involves saving data to a database using Mongoose. One specific field in the database is the 'thumbnail' field, which needs to be filled with a base64 converted file after the file is uploaded to the serve ...

Is it possible to conceal a table element using [hidden] in Angular 2?

I have a table that includes buttons for adding rows. Table application Question: I am looking to hide the table element and add a show click event on the "Add" button. Here is an example of the HTML code: <div class="col-md-12"> <div class="pa ...

Just completed the upgrade of my Angular project from version 9 to version 12, but now encountering issues with a module that utilizes Plotly

Here is the content of my app module file. All components and imports are in their respective places as specified in the documentation: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from &apos ...

The incredible power of the MongoDB $inc field

I am facing a challenge in writing a function that accepts a record id, an action (inc or dec), and a field name as a string to be incremented (can be 'likes', 'subs' or any other). The issue is that I am unable to find a way to replac ...

Steps to resolve the issue with "Error: StaticInjectorError(AppModule)[NgbDropdown -> ChangeDetectorRef]"

My attempt at creating a web app using Angular resulted in successful compilation with no errors. However, upon execution, the browser displays a blank page accompanied by the following error message: ERROR Error: Uncaught(in promise): Error: St ...

Angular and the challenges of connecting Facebook OAuth due to CORS problem

In my API, I have implemented OAuth login and callback methods for popular platforms such as Facebook, Google, and Twitter. The API is built using Express.js framework and it runs on port 3000. Meanwhile, I also have an Angular 2 application running on p ...

Guidelines for accessing a specific object or index from a dropdown list filled with objects stored in an array

Here is a question for beginners. Please be kind. I have created a select field in an HTML component using Angular, populated from an array of objects. My goal is to retrieve the selection using a method. However, I am facing an issue where I cannot use ...

Manage interfaces and structures

I am looking to implement user roles in my application. Here is a snippet of the code I would like to use: export interface User{ name: string roles: Roles[] } interface Roles{ ADMIN: new Permissions(1,1,1,1,1), MOD: new Permissions(1,0,1,1,0,0), [. ...

Executing Angular CLI tasks using a script file rather than directly from the CLI? Embracing the power of Localization and Internationalization

Our Angular 2 app is gearing up for internationalization/localization, and I am looking to create scripts that can handle tasks such as generating translation source files or building/serving the application with translations in a specific language. Inste ...

Creating intricate structures using TypeScript recursively

When working with Angular and TypeScript, we have the power of generics and Compile-goodness to ensure type-safety. However, when using services like HTTP-Service, we only receive parsed JSON instead of specific objects. Below are some generic methods that ...