Search code examples
angulartypescriptrxjsbehaviorsubject

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.

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.