输入'{键:字符串; }' 不可分配给类型 'Product' Angular 7

Type '{ key: string; }' is not assignable to type 'Product' Angular 7

当我将 Product 接口类型添加到数组产品变量时,我遇到了这个问题 "Type '{ key: string; }' is not assignable to type 'Product'."。

这是我的代码:

product.ts

export interface Product {
    title: string;
    price: number;
    category: string;
    imageUrl: string;
}

productService.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  constructor(private db: AngularFireDatabase) { }

  create(product){
    return this.db.list('/products').push(product);
  }

  getAll(){
    return this.db.list('/products').snapshotChanges()
      .pipe(
        map(actions =>
          actions.map(a => ({ key: a.key, ...a.payload.val() }))
        )
      );
  }

  get(productId){
    return this.db.object('/products/' + productId).valueChanges();
  }

  update(productId, product){
    return this.db.object('/products/' + productId).update(product);
  }

  delete(productId){
    return this.db.object('/products/' + productId).remove();
  }
}

admin-product.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ProductService } from 'src/app/product.service';
import { Subscription } from 'rxjs';
import { Product } from 'src/app/models/product';

@Component({
  selector: 'app-admin-products',
  templateUrl: './admin-products.component.html',
  styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent implements OnInit, OnDestroy {
  products: Product[];
  filteredProducts: any[];
  subscription: Subscription;
  dataSource;
  displayedColumns: string[] = ['title', 'price', 'action'];

  constructor(private productService: ProductService){
    this.subscription = this.productService.getAll().subscribe(products => this.filteredProducts = this.products = products);
  }

  ngOnInit() { }

  filter(query: string){
    if(query){
      this.filteredProducts = this.products.filter(p => p.title.toLowerCase().includes(query.toLowerCase()));
    }else{
      this.filteredProducts = this.products;
    }
  }

  ngOnDestroy(){
    this.subscription.unsubscribe();
  }
}

终端错误

ERROR in src/app/admin/admin-products/admin-products.component.ts(19,100): error TS2322: Type '{ key: string; }[]' is not assignable to type 'Product[]'.

src/app/admin/admin-products/admin-products.component.ts(19,100): 错误 TS2322: 输入 '{ key: string; }[]' 不可分配给类型 'Product[]'。 输入'{键:字符串; }' 不可分配给类型 'Product'。 属性 'title' 类型中缺少 '{ key: string; }'.

有人能帮帮我吗?

你可以 console.log 在 this.db.list('/products').snapshotChanges() 中返回的 observable 并查看它上面的参数,可能有更多的东西只是一个 Product 所以你必须从这个 Observable 中选择你想要的.

最有可能的问题是,您正在尝试使用从您的服务返回的通用对象作为类型化对象。我喜欢用 .mapObject.assign() 来隐藏东西,像这样:

  getAll(){
    return this.db.list('/products').snapshotChanges()
      .pipe(
        map(actions =>
          actions.map(a => (Object.assign(new ClassThatImplementsProductInferface(), a))
        )
      );
  }

这假定从 snapshotChanges() 返回的数据包含所有数据并且可能是产品接口。

仅供参考,

您似乎已经映射并为提到的名称(键)分配了值。

getAll(){
    return this.db.list('/products').snapshotChanges()
      .pipe(
        map(actions =>
          actions.map(a => ({ key: a.key, ...a.payload.val() })) //here you have made something strange.
        )
      );
  }

解决方法:- 您需要映射适当的接口模型变量。

example,
  .map( {title: a.something;
    price: a.something;
    category: a.something;
    imageUrl: a.something
})

感谢大家的回放。

在你的帮助下,我使用这段代码成功运行了 Karnan Muthukumar:

getAll(){
    return this.db.list('/products').snapshotChanges()
      .pipe(
        map(actions =>
          actions.map(a => ({ key: a.key, ...a.payload.val() } as Product))
        )
      );
  }

快速解决方案是 ,如果您确实知道响应类型。

(actions as unknown)as Product