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
?
6 Réponses :
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/`); }
note: cela nécessite "import {Observable} de 'rxjs';" dans la classe de service
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/`); }
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; }); } }
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; }
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();
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.
getProducts()
est défini pour renvoyer unObservable
pour un seulProduct
, mais vous affectez le résultat observé à un tableauProduct[]
.Petite correction. Changez le type pour array
return this.http.get<Product[]>(api/products/v1/);
Merci @JoachimSauer, c'était trop facile à voir;) Ça marche!