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

Steps for displaying detailed information about a single product on an Ecommerce page

Currently in the process of developing my Ecommerce project, I have successfully created a product grid with links to each specific product. However, I am facing an issue where I am unable to view the data of each individual item. Below is the code for my ...

Unlocking the power of variables in Next.js inline sass styles

Is there a way to utilize SASS variables in inline styles? export default function (): JSX.Element { return ( <MainLayout title={title} robots={false}> <nav> <a href="href">Title</a> ...

Leverage es6 classes along with mongoose in typescript to utilize loadClass functionality

I've been struggling with a problem and despite my exhaustive search on Google, I still haven't found a solution. My issue revolves around incorporating es6 classes with mongoose using the schema.loadClass(class) method. Unfortunately, when worki ...

When using the TypeScript && operator, the resulting type is not determined by the second operand

Several past discussions on SO have touched upon the concept that the inferred type from && is based on the last expression. TypeScript’s failure to detect union type with an && operator Uncovering the reason behind the && opera ...

What is the process for an Angular Component to receive a return object from a service following an HTTP

I am currently working with angular 4. Is there a way to retrieve an object from a service in this framework? export class LoginRequest { username : string; password : string; } export class LoginResponse { token : string; message : string; sta ...

Warning: NgOptimizedImage Optimization_NOTICE

Exploring the latest features of angular 15 to enhance image performance led me to encounter this cautionary message. `The NgOptimizedImage directive (used on an <img> element with `ngSrc="/assets/fascinating.png") has detected that the ori ...

Receive regular updates every week for an entire month using Javascript

How can I calculate the number of check-ins per week in a month using Javascript? I have been unable to find relevant code for this task. Specifically, I am interested in determining the total count of user check-ins on a weekly basis. For example, if a u ...

Using Typescript generics within a callback function

I am currently working on developing a versatile service that can fetch data from a remote source and create objects based on that data. @Injectable() export class tService<T> { private _data: BehaviorSubject<T[]> = new BehaviorSubject([]) ...

Can a custom type guard be created to check if an array is empty?

There are various methods for creating a type guard to ensure that an array is not empty. An example of this can be found here, which works well when using noUncheckedIndexedAccess: type Indices<L extends number, T extends number[] = []> = T["le ...

Ensuring Type Safety in Typescript

I have a specific requirement where I need to validate the structure of a request body to ensure it conforms to a predefined type. Is there a way or a package that can help achieve this validation? type SampleRequestBody = { id: string; name: string; ...

Having trouble initialising an array of objects in TypeScript? (TS1109: Expression expected)

While working on my project, I encountered a problem when trying to create an array of objects: Error TS1110: Type expected Error TS1109: Expression expected https://i.sstatic.net/Y5qb8.png This is how my array is structured: export let COUNTRIES: A ...

Error in TypeScript: The type 'Color' cannot be assigned to the type '"default" | "primary" | "secondary"'

Currently, I am utilizing MUI along with typescript and encountering the following issue. It seems like I may be overlooking a fundamental concept here but unfortunately cannot pinpoint it. Error: Type 'Color' is not assignable to type '&quo ...

Implementing conditional properties in Typescript based on the value of another property

Is it possible to make a property required in a type based on the presence of another property? Here's an example: type Parent = { children?: Child[]; childrenIdSequence: string[]; // This property should only be required when `children` is prov ...

How Typescript Omit/Pick erases Symbols in a unique way

Recently, I have delved into TypeScript and started working on developing some custom utilities for my personal projects. However, I encountered an issue with type mapping involving Pick/Omit/Exclude and other typing operations where fields with symbol key ...

Differences in Array<T>.filter declaration and application

One issue that I'm currently facing involves a discrepancy between the usage of Array<T>.filter and the interface definition. In an Angular2 component, I have implemented the following filter: performFilter(filterBy: string): IProduct[] { ...

Issue with Ionic 3 subscribes triggering repeatedly

I've been struggling with the code for an Ionic taxi app for a few weeks now. My main issue is that whenever the page loads, the subscription gets triggered multiple times along with other functions within it. The same problem occurs when any travel i ...

Formcontrol is not functioning properly with invalid input

I am attempting to style an input field with a FormControl using the :invalid pseudo-class. Here is my code snippet: scss input:invalid { background-color: red; } html <input type="text" [formControl]="NameCtrl"> Unfortunate ...

Having trouble accessing the object from @Input

My issue revolves around system.component.html <div *ngFor="let tab of tabs | async"> <app-tab [tab]="tab"></app-tab> </div> In tab.component.ts, I wrote the following code: export class TabComponent implements OnInit { @Inpu ...

Incorporate form information into an array in Angular Version 2 or higher

This form is where I craft my questions https://i.sstatic.net/93781.png When composing a question, the ability to include multiple alternatives is available. There will also be an option to edit these alternatives. The desired format for my array is as ...

Suggested imports in a yarn monorepo are not being automatically added when selected

I've noticed that many people are asking similar questions, but my situation seems a bit unique as I haven't found anyone else with the same issue. Currently, I'm working on a file in packages/frontend/client, specifically packages/frontend ...