【问题标题】:Error occur in angular like Type '{}' is not assignable to type 'Product[]'. Property 'length' is missing in type '{}'像类型“{}”这样的角度发生错误不能分配给类型“产品[]”。类型“{}”中缺少属性“长度”
【发布时间】:2019-09-05 18:57:01
【问题描述】:

我是新的 Angular 开发人员,我遵循 Angular cli 所需的规范 - Angular CLI:7.0.7 节点:10.13.0 操作系统:win32 x64 Angular:7.0.4 但是发生了 1 个错误。错误是

src/app/products/products.component.ts(28,12) 中的错误:错误 TS2322: 类型“{}”不可分配给类型“Product[]”。属性“长度” 类型“{}”中缺少。

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();
  }
} 

以下行发生错误 .switchMap(products => { this.products = 产品; // 此行发生错误 return route.queryParamMap;

【问题讨论】:

    标签: angular


    【解决方案1】:

    正确的方法是像这样在您的服务中添加输入

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

    这会将您的响应类型转换为 Observable&lt;Product[]&gt; 并且错误将消失

    【讨论】:

    • 这是正确的解决方案,必须在拿到对象时进行检查,而不是在其他地方强制
    【解决方案2】:

    你可能想改变

    .switchMap(products => {
    ...
    } 
    

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

    【讨论】:

      猜你喜欢
      • 2021-05-27
      • 1970-01-01
      • 2020-06-02
      • 2018-09-08
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 2017-12-05
      相关资源
      最近更新 更多