labrapoo
labrapoo

Reputation: 25

Why is this value considered undefined everywhere else in Angular?

I have Books, and Reviews objects.

      books: Book[];
  reviews: Review[];

The information to fill these arrays are pulled in by a component's functions.

  retrieveBooks(): void {
    this.bookService.getAll()
      .subscribe(
        data => {
          this.books = data;
        },
        error => {
          console.log(error);
        }
      );
  }

  retrieveReviews(): void {
    this.reviewService.getAll()
      .subscribe(
        data => {
          this.reviews = data;
        },
        error => {
          console.log(error);
        });
  }

The code works, but the array of objects are not recognized.

It says undefined.

Unless I work within the .subscribe ( data => { } )

I could put in a console.log, and the array prints as it should.

But if I try to read the array outside of this function, it will still say undefined.

I don't understand why this is the case, since we've written it to the components arrays we define in the beginning.

Shouldn't this data be accessible throughout the entire component?

Upvotes: 1

Views: 1103

Answers (1)

Rob Monhemius
Rob Monhemius

Reputation: 5144

You only defined the type. The property has no value assigned, thus it returns undefined. You should initialise an empty array beforehand.

@Component(){}
export class MyComponent {
  books: Book[] = [];
  reviews: Review[] = [];

  ... more stuff
}

Sidenote: Before you assign the values of books and reviews in subscribe, which takes some time, the value is undefined ( or in my case []).

Upvotes: 1

Related Questions