Data from the observable is always undefined

Viewed 292

I have a service which return observables of an object array

allFruits: Fruit[] = [
    {
      id: "1",
      name: "fruit 1"
    },
    {
      id: "2",
      name: "fruit 2"
    },
    {
      id: "3",
      name: "fruit 3"
    },
    {
      id: "4",
      name: "fruit 4"
    }
  ];
function getFruits {
 return of(allFruits);
}

Component

allFruits: Observable<Fruit[]>;
constructor(
    private fruitService: FruitService
  ) {
    this.fruitService
       .getFruits()
       .pipe(first())
       .subscribe(() => {
        results => this.allFruits == results;
      });

this.allFruits is always undefined and it does not have any values in there. If I do console.log(results) I do get the values

3 Answers

You must not use equality operater == instead of = assignment operator.

allFruits: Observable<Fruit[]>;
constructor(
    private fruitService: FruitService
  ) {
    this.fruitService
       .getFruits()
       .pipe(first())
       .subscribe(() => {
        results => this.allFruits = results;
      });

I'm assuming that you want allFruits to be an array rather than an Observable. Is that correct? I also changed the subscribe lambda function a little.

allFruits: Fruit[];
constructor(
    private fruitService: FruitService
  ) {
    this.fruitService
       .getFruits()
       .pipe(first())
       .subscribe(results => {
        this.allFruits == results;
      });

If your intent is to use this service in conjunction with the async pipe, you could do something like the following:

allFruits: Observable<Fruit[]>;
constructor(
    private fruitService: FruitService
  ) {
    this.allFruits = this.fruitService
       .getFruits()
       .pipe(first());

You can then use allFruits with the async pipe in your template.

allFruits: Observable<Fruit[]>;
constructor(
    private fruitService: FruitService
  ) {
    this.fruitService
       .getFruits()
       .pipe(first())
       .subscribe(() => {
        results => this.allFruits = results;
      });

But here first() operator will return first obj which is not of type Array either you should not use Array type or you should remove first() pipe

Related