reyesoft / ngx-jsonapi

JSON API client library for Angular 5+ 👌 :: Production Ready 🚀
https://ngx-jsonapi.reyesoft.com/
MIT License
101 stars 52 forks source link

Access to element of array is undefined #318

Closed mangeleptico closed 3 years ago

mangeleptico commented 3 years ago

When i try to access to any element of authors array, the response is undefined, only works when i change to books table and then return to authors. This happends with all get a collection of resources

example: ` public authors: DocumentCollection;

public constructor(private route: ActivatedRoute, private authorsService: AuthorsService, booksService: BooksService) {
    route.queryParams.subscribe(({ page }) => {
        authorsService
            .all({
                include: ['books'],
                sort: ['name'],
                page: { number: page || 1 },
                ttl: 3600
            })
            .subscribe(
                authors => {
                    this.authors = authors;
                },
                error => console.error('Could not load authors :(', error)
            );
    });
}

ngOnInit(): void  {
     console.log(this.authors.data); // No problem
    console.log(this.authors.data[0]); // Here the value is undefined
}`
pandabamboo90 commented 3 years ago

@mangeleptico

I had the same problem before :) You can use filter operator from RxJS to get the resources when it has been "built & loaded" before assign it to your data variable

    authorsService
      .all({
        include: ['books'],
        sort: ['name'],
        page: { number: page || 1 },
        ttl: 3600
      })
      .pipe(
        filter(authors => authors.loaded), // Only get the response when every resources are loaded !
      )
      .subscribe(
        authors => {
          this.authors = authors;
        },
        error => console.error('Could not load authors :(', error)
      );
mangeleptico commented 3 years ago

Thanks! its works for me. It's necessary too use a conditional of authors in html if i want to print authors data on screen to avoid asynchronous errors

niskah-energies commented 2 years ago

Hi,

If I try to user filter(), I have an error:

TypeError: filter is not a function. (In 'filter(function (authors) { return authors.loaded; })', 'filter' is undefined)