pune
pune

Reputation: 99

Error occur in angular like Type '{}' is not assignable to type 'Product[]'. Property 'length' is missing in type '{}'

I'm fresher angular developer i have following specification that require for angular cli - Angular CLI: 7.0.7 Node: 10.13.0 OS: win32 x64 Angular: 7.0.4 But there is 1 error occur .error is

ERROR in src/app/products/products.component.ts(28,12): error TS2322: Type '{}' is not assignable to type 'Product[]'. Property 'length' is missing in type '{}'.

product.component.ts

import { Product } from 'src/app/models/product';
import { ActivatedRoute } from '@angular/router';
import { CategoryService } from './../category.service';
import { ProductService } from './../product.service';
import { Component } from '@angular/core';
import 'rxjs/add/operator/switchMap';


@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
export class ProductsComponent {
  products: Product[] = [];
  filteredProducts: Product[] = [];
  categories$;
  category: string;

  constructor(
    route: ActivatedRoute,
    productService: ProductService,
    categoryService: CategoryService
  ) {
    productService
      .getAll()
      .switchMap(products => {
        this.products = products;
        return route.queryParamMap;
      })

      .subscribe(params => {
        this.category = params.get('category');

        this.filteredProducts = (this.category) ?
          this.products.filter(p => p.category === this.category) :
          this.products;
      });

    this.categories$ = categoryService.getAll();
  }
} 

Error occur on following line .switchMap(products => { this.products = products; // Error occure on this line return route.queryParamMap;

Upvotes: 0

Views: 295

Answers (2)

Khang Luong
Khang Luong

Reputation: 118

You might want to change

.switchMap(products => {
...
} 

to

.switchMap((products: Product[]) => {
...
}

Upvotes: 0

Andrei
Andrei

Reputation: 12196

the right way would be to add typing to your service like this

class ProductService {
  getAll() {
    this.http.get<Product[]>(...);
  }
}

this will cast your response type to Observable<Product[]> and error will disappear

Upvotes: 1

Related Questions