ngx pagination for Observable array

Viewed 69

when ı use ngx pagination for item : Array< any> = [] there is no problem but when use for items: Observable<any[]> ı am getting an error :

Error: src/app/home-page/home-page.component.html:18:36 - error TS2345: Argument of type 'any[] | null' is not assignable to parameter of type 'Collection< unknown>'.

18 <li *ngFor="let item of items | async | paginate: { itemsPerPage: 12, currentPage: p }">{{ item }}

how can fix it ?

home.html :

 <div >
        <ul>
            <li *ngFor="let item of items | async  | paginate: { itemsPerPage: 12, currentPage: p }">{{ item }}</li>
        </ul>
        <pagination-controls (pageChange)='p = $event'></pagination-controls>
</div>

home.ts

import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/compat/database';
import { Observable } from 'rxjs/internal/Observable';
import { ProductService } from '../services/product.service';
import { UserServiceService } from '../services/user-service.service';


@Component({
  selector: 'app-home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
 
  items: Observable<any[]>  ;

  constructor(private db : AngularFireDatabase,private userS : UserServiceService,private pd: ProductService ) {
   this.items = this.pd.items
  }

product.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/compat/database';
import { map } from 'rxjs';
import { Observable } from 'rxjs/internal/Observable';
import { UserServiceService } from './user-service.service';

@Injectable({
  providedIn: 'root'
})
export class ProductService {
  items: Observable<any[]>;
  constructor(private db: AngularFireDatabase,private userS : UserServiceService) {
    this.getProducts()
  }
  getProducts(){
    this.items = this.db.list("collections").snapshotChanges().pipe(
      map(changes =>
        changes.map(c => ({ key: c.payload.key, ...c.payload.val() as {} }))

      )
    );
  }
}

1 Answers

The type is getting lost inside the javascript map, here you need to just manually set it like so.

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/compat/database';
import { map } from 'rxjs';
import { Observable } from 'rxjs/internal/Observable';
import { UserServiceService } from './user-service.service';

@Injectable({
  providedIn: 'root'
})
export class ProductService {
  items: Observable<any[]>;
  constructor(private db: AngularFireDatabase,private userS : UserServiceService) {
    this.getProducts()
  }
  getProducts(){
    this.items = <Observable<Array<any>>>this.db.list("collections").snapshotChanges().pipe(
      map(changes =>
        <Array<any>>changes.map(c => <any>({ key: c.payload.key, ...c.payload.val() as {} }))
      )
    );
  }
}
Related