Always[] contains all properties needed

I received a basic JSON response containing a single object. My intention was to display this on an HTML page, but unfortunately I encountered the following error:

src/app/games/game.component.ts:35:7 - error TS2740: Type 'never[]' is missing the following properties from type 'GAMEDETAIL': id, title, releasedate, description, and 6 more

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';

interface GAMEDETAIL {
  id: number,
  title: string
  releasedate: number
  description: string,
  adddate: string,
  changedate: string,
  pdffile: string,
  youtubelink: string,
  images: any,
  producer: any
}

@Component({
  selector: 'app-game',
  templateUrl: './game.component.html',
  styleUrls: ['./game.component.css']
})

export class GameComponent implements OnInit {

  private data:any = [];  
  gamedetail:GAMEDETAIL;
  gameid: number = 0;

    constructor(private route: ActivatedRoute, private http:HttpClient) {
      **this.gamedetail = [];**
    }

    ngOnInit(): void {
      this.gameid = parseInt( this.route.snapshot.paramMap.get('id') as string );

      this.getJSON(this.gameid).subscribe(data => {
        console.log(this.gamedetail.title);

    });
    }

    getJSON(spielid: Number): Observable<GAMEDETAIL[]> {
      return this.http.get<GAMEDETAIL[]>("https://example.org/api/gamedetail/" + spielid);
    }

}

Upon checking the console, I found the following JSON Data:

{
    "id":1,
    "title":"Ligretto",
    "releasedate":2000,
    "producer":[
    {
        "company":"Schmidt",
        "url":"https://example.org"
    }
    ],
    "pdffile":"https://example.org",
    "discription":"This is the game's description",
    "images":[
    {
        "position":0,
        "imagefile":"https://example.org"
    },
    {
        "position":1,
        "imagefile":"https://example.org"
    }
    ],
    "youtubelink":"https://example.org",
    "adddate":"2021-12-22 22:22:44",
    "changedate":"2022-01-11 11:11:20"
}        

I attempted to log the line below using the console:

console.log(this.gamedetail.title);

However, I encountered issues while trying to compile it.

Answer №1

Based on the JSON provided, it appears to be a single object.

Here are some key errors that need to be addressed:

Error 1: The variable gamedetail is declared as type GAMEDETAIL, but then assigned an empty array [].

It's incorrect to assign an empty array to gamedetail since it conflicts with its type definition.

gamedetail: GAMEDETAIL;
constructor(private route: ActivatedRoute, private http:HttpClient) {
  **this.gamedetail = [];**
}

Solution for Error 1

Remove the assignment of an empty array in the constructor.

constructor(private route: ActivatedRoute, private http:HttpClient) { }

Note: It's recommended to initialize variables in the ngOnInit() method instead of the constructor. Refer to this link for more details.


Error 2: The http.get should expect to receive a GAMEDETAIL object.

Since the JSON returns a single object, the http.get method should not expect to receive an array of GAMEDETAIL and should return an observable of GAMEDETAIL instead.

getJSON(spielid: Number): Observable<GAMEDETAIL[]> {
  return this.http.get<GAMEDETAIL[]>("https://example.org/api/gamedetail/" + spielid);
}

Solution for Error 2

Modify the getJSON method as follows:

getJSON(spielid: Number): Observable<GAMEDETAIL> {
  return this.http.get<GAMEDETAIL>("https://example.org/api/gamedetail/" + spielid);
}

Error 3: It's missing the assignment of the value to gamedetail within the subscribe method.

this.getJSON(this.gameid).subscribe((data) => {
  console.log(this.gamedetail.title);
});

Solution for Error 3

Make sure to assign the retrieved data to gamedetail within the subscribe method.

this.getJSON(this.gameid).subscribe((data) => {
  this.gamedetail = data;
  console.log(this.gamedetail.title);
});

Here is a sample demo on StackBlitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a ReferenceError stating that HTMLInputElement is not defined while using Angular 4 Universal

I am currently working on migrating my Angular 4 app from a CDN to Angular Universal due to issues with Google crawler not properly indexing my site. However, I have encountered an error while trying to run my Node server script: @ViewChild('text&apo ...

Creating Custom Message Boxes with Excel Online Script

Currently in the process of migrating all my VBA scripts to Excel Online automation. Does anyone know how to convert MsgBox from VBA to Excel Online automation? Example: MsgBox "Some Text" I am linking my code to buttons for users to click on. I want to ...

When implementing 'useGlobalGuards' in NestJS, remember to exclude endpoints for enhanced security

After implementing the useGlobalGuards method in my main.ts file, all endpoints now utilize the AuthGuard. This guard triggers a 401 error if a valid auth token is not present in the request header. Previously, I used @UseGuards(AuthGuard) on individual cl ...

Oops! TypeScript error TS2740: The type 'DeepPartial<Quiz>[]' is currently missing key properties from type 'Question': id, question, hasId, save, and a few more

I'm struggling to resolve this error. Can anyone provide guidance on what needs to be corrected in order for this code to function properly? import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm& ...

How can I convert an XML response to JSON in an Ionic 2 HTTP request

Hey there, I'm currently working on making an http request from this rss feed. Here's what I have so far: makeRequest() { this.http.get('http://www.gazetaexpress.com/rss/auto-tech/?xml=1') .subscribe(data => { ...

Unable to execute an HTTPS request while in server-side rendering

Encountering a frustrating error with https calls from the server that reads as follows: Http failure response for (unknown url): 0 Unknown Error. Within my Angular application, when an https call is executed in the browser, everything runs smoothly. Howe ...

SignalR Negotiate in AspNetCore 2.2 with Angular consistently triggers a 404 error indicating page not found

I am currently using: AspNetCore 2.2 Web Application Angular CLI: 8.3.3 Node: 10.16.0 OS: Windows 32-bit x64 Angular: 6.1.10 services.AddSignalR(); app.UseSignalR(config => { config.MapHub<NotificationHub>("/notify"); }); this.hubConnection.st ...

Encountered an issue when making an Angular2 HTTP POST request - SyntaxError: JSON input unexpectedly ended

Encountering an issue while trying to post data from Angular2 to a NodeJS backend. Although the POST request is successful and the server logs the correct data, an error is displayed in the browser: An error occurred: SyntaxError: JSON.parse: unexpected ...

Having trouble with Angular routing when attempting to directly access a specific URL path?

Seeking help with my routing setup in Angular. Using v12 of Angular. Encountering a 404 Not Found error when trying to access the direct URL for "register" at somesite.com/register. Uncertain if this is a server or Angular issue. Here is my router module ...

Incorrect tsx date interpretation when dealing with years such as 0022

I am facing an issue with dates in tsx. The problem lies in the fact that when I set a date like 30/11/0022, it interprets the date as 30/11/1922, which is incorrect. Here is the input element I have in tsx: <FormikField name="Birthdate" disa ...

The function signature '(close: () => void) => ReactElement' cannot be assigned to type 'ReactNode'

While attempting to utilize @Reactjs-popup, I came across this example. However, when trying to implement it in TypeScript and accessing the close function, an error is displayed. Type '(close: () => void) => ReactElement' is not assignable ...

Creating a TypeScript constructor for the parent class that accesses the properties of the child class

abstract class Parent { public foo: string; constructor(v: Partial<Parent>) { Object.assign(this, v); } } class ChildA extends Parent { bar: string; } class ChildB extends Parent { baz: string } In this scenario, const a = new Child ...

"RxJS in Angular 2: The elusive map function seems to be missing

Issue: Received an error stating, "Property 'map' does not exist on type 'Observable'." import { Component } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; decl ...

Angular HTML prints only halfway down the page when document is printed

While utilizing document.write(), I encountered an issue when printing the contents of an object specifically formatted for a printer. The text started printing only halfway down the page. I can successfully print the screen without any problems, which ma ...

What is the process for incorporating a personalized inputComponent JSX <input /> into a react-phone-number-input PhoneInput component?

Instructions to follow when working with code. react-phone-number-input provides the option for users to replace its default <input /> JSX tag with a custom one, requiring the type React.ForwardRefExoticComponent<React.InputHTMLAttributes<HTML ...

Implementing the change method in Angular2 and JavaScript

Within my application, I have implemented two select elements. The objective is that when one select element is altered, the other will automatically change as well. Furthermore, I need to be able to detect the event when the second select element is modif ...

The issue arises when the mat-panel-description is not properly aligned with the shrinking panel

Within my HTML, I have a mat-panel with a description that is populated by a variable from the TS file. However, I am encountering an issue where if I shrink the panel and the description is too long, the text is cut off at the top and bottom. Is there a w ...

What is the process for sending a GET request with a URL-encoded object in Angular?

I am struggling with a complex object: { valueA:'a', value_array: { 'v': {value:1, value:2}, 'v2': {value:1, value:2}, } } Is there a way to encode it as a URL string for a GET request using Angular's HTTP servic ...

The ASP.NET Core 3.0 Web API method consistently encounters null values

I've encountered an issue with my Angular app where it displays a 500 server error. Here are the methods I'm using: /*Product Service*/ addNewProduct(newProduct: Product): Observable<Product> { console.log(newProduct); return this.http.po ...

Exploring Typescript Reflection: The Importance of Required Parameters and Default Values

In summary: Is there a method to determine whether a typescript parameter is mandatory and/or has a preset value? Expanding further: Imagine I have the code snippet below: //Foo.ts class Bar { foo(required:string,defaultValue:number=0,optional?:boole ...