2
votes

Tapez '{clé: chaîne; } 'n'est pas attribuable au type' Produit 'Angular 7

J'ai ce problème "Le type '{key: string;}' n'est pas attribuable au type 'Produit'." lorsque j'ajoute à une variable array products le type d'interface Product.

Voici mon code:

product.ts

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

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

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

erreur de terminal

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

src / app / admin / admin-products / admin-products.component.ts (19 100 ): erreur TS2322: Tapez '{clé: chaîne; } [] 'n'est pas attribuable au type' Produit [] '. Tapez '{clé: chaîne; } 'n'est pas attribuable au type' Produit '. La propriété 'title' est manquante dans le type '{key: string; } '.

Quelqu'un pourrait-il m'aider s'il vous plaît?


1 commentaires

Quels types sont dans observable renvoyés par this.db.list ('/ products'). snapshotChanges () ?


4 Réponses :


0
votes

Vous pouvez console.log l'observable retournée dans this.db.list ('/ products'). snapshotChanges () et voir quels paramètres sont dessus, il y a probablement plus de chose que Produit donc vous devrez choisir ce que vous voulez de cet observable.


0 commentaires

0
votes

Le problème le plus probable est que vous essayez d'utiliser un objet générique renvoyé par votre service en tant qu'objet typé. J'aime utiliser .map et Object.assign () pour cacher des choses, comme ceci:

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

Cela suppose que les données sont retournées de snapshotChanges () a toutes les données et pourrait être une interface produit.


0 commentaires

2
votes

Juste pour une suggestion,

Il semble que vous ayez mappé et attribué une valeur à un nom (clé) mentionné.

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

Solution: - Vous avez besoin d'une variable de modèle d'interface appropriée pour la carte.

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


1 commentaires

Merci pour votre rediffusion @Karnan Muthukumar. Je l'ai fait fonctionner en utilisant ce code avec votre aide: getAll () {return this.db.list ('/ products'). SnapshotChanges () .pipe (map (actions => actions.map (a => ({clé: a.key, ... a.payload.val ()} en tant que produit)))); }



1
votes

Merci d'avoir rejoué à tous.

Je l'ai fait fonctionner en utilisant ce code avec votre aide Karnan Muthukumar:

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


2 commentaires

La clé n'est toujours pas disponible sur l'interface du produit si vous souhaitez l'utiliser plus tard. Vous pouvez simplement l'ajouter à l'interface, ce qui permettrait à d'autres endroits d'utiliser cette propriété. De cette façon, vous n'aurez pas à convertir le type en produit, cela fonctionnera simplement.


Droit sur ajouter la clé à l'interface ont encore besoin de ce "comme produit" pour sauver la journée propre et simple!