64
votes

Typographie: il manque les propriétés suivantes du type Y length, pop, push, concat et 26 autres. [2740]

J'ai cette interface produit:

export class ShopComponent implements OnInit {
    public productsArray: Product[];
    
    ngOnInit() {
        this.productService.getProducts().subscribe(res => {
          this.productsArray = res;
        });
    }
}

Service avec méthode appelant le point de terminaison du produit:

  public getProducts(): Observable<Product> {
    return this.http.get<Product>(`api/products/v1/`);
  }
  

Et composant où j'utilise ce service pour obtenir les produits.

export interface Product{
  code: string;
  description: string;
  type: string;
}

Avec cet état, j'obtiens une erreur:

[ts] Le type 'Product' ne contient pas les propriétés suivantes du type 'Product []': length, pop, push, concat et 26 autres. [2740]

La suppression de la saisie sur les productsArray variable tableau supprime l'erreur, mais vous ne comprenez pas pourquoi cela ne fonctionne pas, car la réponse du serveur est un tableau d'objets du type Products ?


3 commentaires

getProducts() est défini pour renvoyer un Observable pour un seul Product , mais vous affectez le résultat observé à un tableau Product[] .


Petite correction. Changez le type pour array return this.http.get<Product[]>(api/products/v1/);


Merci @JoachimSauer, c'était trop facile à voir;) Ça marche!


6 Réponses :


68
votes

Vous retournez Observable<Product> et vous vous attendez à ce qu'il s'agisse du Product[] dans le rappel d' subscribe .

Le type renvoyé par http.get() et getProducts() doit être Observable<Product[]>

public getProducts(): Observable<Product[]> {
    return this.http.get<Product[]>(`api/products/v1/`);
}


1 commentaires

note: cela nécessite "import {Observable} de 'rxjs';" dans la classe de service



15
votes

Vous avez oublié de marquer le type de retour getProducts comme un tableau. Dans votre getProducts, il est indiqué qu'il renverra un seul produit. Alors changez-le en ceci:

public getProducts(): Observable<Product[]> {
    return this.http.get<Product[]>(`api/products/v1/`);
  }


0 commentaires

4
votes

Pour les débutants comme moi, n'attribuez pas de variable à la réponse du service, c'est-à-dire

export class ShopComponent implements OnInit {
    public productsArray: Product[];

    ngOnInit() {
        this.productsArray = this.productService.getProducts().subscribe();
    }
}

Au lieu de

export class ShopComponent implements OnInit {
  public productsArray: Product[];

  ngOnInit() {
      this.productService.getProducts().subscribe(res => {
        this.productsArray = res;
      });
  }
}


0 commentaires

2
votes

J'ai eu le même problème et je l'ai résolu comme suit définir une interface comme la mienne

 constructor(private notificationService: NotificationService) {
   }

  ngOnInit() {
      /* get Notifications */
      this.notificationService.getNotifications().subscribe(data => this.notifications = data);
}

et en nofificationService écrire

allNotifications: Notification[]; 
  //NotificationDetail: Notification;  
  private notificationsUrl = 'assets/data/notification.json';  // URL to web api 
  private downloadsUrl = 'assets/data/download.json';  // URL to web api 

  constructor(private httpClient: HttpClient ) { }

  getNotifications(): Observable<Notification[]> {    
       //return this.allNotifications = this.NotificationDetail.slice(0);  
     return this.httpClient.get<Notification[]>

(this.notificationsUrl).pipe(map(res => this.allNotifications = res))
      } 

et en écriture de composants

export class Notification {
    id: number;
    heading: string;
    link: string;
}


0 commentaires

0
votes

Cette erreur peut également être due au fait que vous ne vous abonnez pas à Observable.

Exemple, au lieu de:

   this.productService.getProducts().subscribe({
    next: products=>this.products = products,
    error: err=>this.errorMessage = err
   });

faites ceci:

this.products = this.productService.getProducts();


0 commentaires

1
votes

J'ai eu le même message d'erreur sur l'objet d'entrée de la mutation GraphQL, puis j'ai trouvé le problème, en fait, dans mon cas, la mutation attend un tableau d'objets en entrée mais j'essaye d'insérer un seul objet en entrée. Par exemple:

Premier essai

const mutationName = await apolloClient.mutate<insert_mutation, insert_mutationVariables>({
      mutation: MUTATION,
      variables: {
        objects: [{id: 1, name: "John Doe"}],
      },
    });

Appel de mutation corrigé sous forme de tableau

const mutationName = await apolloClient.mutate<insert_mutation, insert_mutationVariables>({
      mutation: MUTATION,
      variables: {
        objects: {id: 1, name: "John Doe"},
      },
    });

Parfois, de simples erreurs comme celle-ci peuvent causer des problèmes. J'espère que cela aidera quelqu'un.


0 commentaires