Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Property 'selectedvalue' is used before its initialization

I’m trying to share the date from service to another component through BehaviorSubject but getting the above error.

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

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

My another Component :

This is where I am subscribing the service.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export class CategorypageComponent implements OnInit {
  constructor(public categoryfood: HomepageService) {}

  ngOnInit(): void {
    const getSharedValue = this.categoryfood.share.subscribe((x) =>
      console.log(x)
    );
  }
}

>Solution :

You are just passing selectedvalue to be BehaviourSubject once. The updates to selectedValue will not be seen by the BehaviourSubject.

Use the .next() method to push changes to the BehaviourSubject.

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)
      })
    );
  }
}

In that case, you don’t need selectedvalue anymore.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading