The Angular code is currently unable to retrieve the quiz ID

Hey there, I am encountering an issue with fetching the Qid from the server side. Interestingly enough, it works perfectly fine in Postman but not in Angular. The problem seems to be isolated to the Quiz ID retrieval, as other IDs like Category ID and Question ID are retrieved correctly.

ViewQuizzesComponent

import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import {  MatCardModule } from '@angular/material/card';
import { RouterLink } from '@angular/router';
import Swal from 'sweetalert2';
import { QuizService } from '../../../services/quiz.service';


interface Quiz {
  qId: number;
  title: string;
  description: string;
  maxMarks: number;
  numberOfQuestions: number;
  active: boolean;
  category: {
    cid: number;
    title: string;
    
  };}

@Component({
  selector: 'app-view-quizzes',
  standalone: true,
  imports: [CommonModule,
    MatCardModule,
    MatButtonModule,
    RouterLink,],
  templateUrl: './view-quizzes.component.html',
  styleUrl: './view-quizzes.component.css'
})
export class ViewQuizzesComponent {
  quizzes: Quiz[] = [];

  constructor(private _quiz: QuizService) {}

  ngOnInit(): void {
    this._quiz.quizzes().subscribe(
      (data: any) => {
        this.quizzes = data;
        console.log(this.quizzes);
      },
      (error) => {
        console.log(error);
        Swal.fire('Error !', 'Error in loading data !', 'error');
      }
    );
  }

  //
  deleteQuiz(qId: number) {
    console.log('Deleting quiz with ID:', qId);
    Swal.fire({
      icon: 'info',
      title: 'Are you sure ?',
      confirmButtonText: 'Delete',
      showCancelButton: true,
    }).then((result) => {
      if (result.isConfirmed) {
        //delete...

        this._quiz.deleteQuiz(qId).subscribe(
          (data) => {
            this.quizzes = this.quizzes.filter((quiz) => quiz.qId !== qId);
            Swal.fire('Success', 'Quiz deleted ', 'success');
          },
          (error) => {
            Swal.fire('Error', 'Error in deleting quiz', 'error');
          }
        );
      }
    });
  }
}

ViewQuizzesComponent HTML

<mat-card class="mt10 mr20 ml20" *ngFor="let q of quizzes">
  <mat-card-header>
    <div mat-card-avatar class="example-header-image"></div>
    <mat-card-title>
      {{ q.title }}
    </mat-card-title>
    <mat-card-subtitle>
      {{ q.category.title }}
    </mat-card-subtitle>
  </mat-card-header>
  <mat-card-content>
    <p>{{ q.description }}</p>
  </mat-card-content>
  <mat-card-actions>
    <button
      [routerLink]="'/admin/view-questions/' + q.qId + '/' + q.title"
      mat-flat-button
      color="accent"
    >
      Questions
    </button>
    <button mat-stroked-button color="accent" class="ml20">
      Max Marks: {{ q.maxMarks }}
    </button>
    <button mat-stroked-button color="accent" class="ml20">
      Questions: {{ q.numberOfQuestions }}
    </button>
    <button
      [routerLink]="'/admin/quiz/' + q.qId"
      mat-flat-button
      color="accent"
      class="ml20"
    >
      Update
    </button>
    <button mat-flat-button color="accent" class="ml20">Attempts</button>

    <button
      mat-flat-button
      color="warn"
      class="ml10"
      (click)="deleteQuiz(q.qId)"
    >
      Delete
    </button>
  </mat-card-actions>
</mat-card>

<div class="container text-center mt20">
  <button routerLink="/admin/add-quiz" mat-raised-button color="accent">
    Add New Quiz
  </button>
</div>

Quiz Service

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import baseUrl from './helper';

@Injectable({
  providedIn: 'root',
})
export class QuizService {
  constructor(private http: HttpClient) {}

  public quizzes() {
    return this.http.get(`${baseUrl}/quiz/`);
  }

  //add quiz
  public addQuiz(quiz: any) {
    return this.http.post(`${baseUrl}/quiz/`, quiz);
  }

  //delete quiz
  public deleteQuiz(qId: number) {
    return this.http.delete(`${baseUrl}/quiz/${qId}`);
  }

  //get the single quiz

  public getQuiz(qId: number) {
    return this.http.get(`${baseUrl}/quiz/${qId}`);
  }

  //update quiz
  public updateQuiz(quiz: any) {
    return this.http.put(`${baseUrl}/quiz/`, quiz);
  }

  //get quizzes of category
  public getQuizzesOfCategory(cid: number) {
    return this.http.get(`${baseUrl}/quiz/category/${cid}`);
  }
  //qet active quizzes
  public getActiveQuizzes() {
    return this.http.get(`${baseUrl}/quiz/active`);
  }

  //get active quizzes of category
  public getActiveQuizzesOfCategory(cid: number) {
    return this.http.get(`${baseUrl}/quiz/active/${cid}`);
  }
}

SpringBoot API https://i.sstatic.net/J8njM.png

The issue here is that the ID is being fetched as undefined, even though the retrieval process seems correct. Any assistance in resolving this problem would be greatly appreciated. https://i.sstatic.net/v84zD.png https://i.sstatic.net/iuLi8.png

Answer №1

When working with JavaScript, the presence of undefined indicates that a property does not exist on an object. It is important to ensure that your JS object includes all the necessary public members from the API Response object when dealing with API responses.

Here are some key points to keep in mind:

  • Verify if the expected property exists on the API Response object:
    • Ensure that the property is public, as the serializer will not include it otherwise.
  • Double-check for typos in either the JS or API Response object properties:
    • Pay attention to the casing settings of the serializer, as property names are case-sensitive.

If possible, consider utilizing automated code generation tools to create JS models that align with the structure of the API Response object.

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

js TouchEvent: When performing a pinch gesture with two fingers and lifting one of them up, how can you determine which finger was lifted?

I am currently working on a challenging touching gesture and have encountered the following issue: let cachedStartTouches: TouchList; let cachedMoveTouches: TouchList; function onStart(ev: TouchEvent) { // length equals 2 when two fingers pinch start ...

The issue with ngModel in Angular is that it fails to update the value within the component

My ngModel doesn't seem to be functioning properly when I use it with a textbox in my application. This is the code snippet from app.component.html: <input type="text" [value]="name" [ngModel]="name"> Name is: {{na ...

Unable to destructure props and assign them to a react-bootstrap component

I recently installed react-bootstrap and I am looking to customize the default buttons in my project. My goal is to simplify the button creation process by just using <Button> without specifying a variant option for most buttons. import * as bs from ...

Why do we often encounter a "SyntaxError: Unexpected token ;" error when a seemingly normal semicolon is present in distribution files?

Currently, I am in the process of developing a newsletter subscription API using node.js and typescript. This project involves my first experience with typeorm and PostgreSQL. Following several tutorials, I configured typeorm and created the entity types a ...

Angular project is inactive

I'm encountering an issue with my Angular project where it's not building. Whenever I try to run the app using 'ng serve -o', I receive the following error message: `An unhandled exception occurred: Cannot find module '@angular-de ...

Calculate the total sum of an array in Angular based on a specific condition of another key

How do I calculate the sum of array elements where sel1, sel2, or sel3 is equal to 1 from the following Array? [ { "sel1": 0, "sel2": 1, "sel3": 0, "price": 10 }, { "sel1": 0, "sel2": 1, &qu ...

Unable to access property 'scrollToBottom' as it is undefined

I'm encountering the error "Cannot read property 'scrollToBottom' of undefined" and haven't been able to find a solution anywhere, hence this post: Here is my use case: I have a custom accordion list, and on click of one of the list i ...

Confusion arises from the error message 'No overload matches this call'

Currently, I am working on a weather application using Angular based on the concepts from the book Angular for Enterprise-Ready Web Applications - Second Edition. I am in the process of adding a search component to the app, which will allow users to displa ...

Is there a way to declare the different types of var id along with its properties in Typescript?

I recently received a task to convert a JavaScript file to a TypeScript file. One issue I am currently facing is whether or not I should define types for the 'id' with this expression, e.g., id={id}. So far, I have tried: Even though I defined ...

Using dangerouslySetInnerHTML in ReactJS can potentially strip away data attributes

After adding a data-test attribute to the a anchor tag within an HTML string and inserting it using dangerouslySetInnerHTML, I noticed that the data attributes are somehow being stripped out. Is there a way to prevent this from happening? These attribute ...

Having trouble with inserting data into Firestore using Firebase cloud functions?

I'm attempting to insert a document from a Firebase cloud function into Firestore, but it's not functioning as expected. Here's my code snippet: import * as admin from "firebase-admin" import * as functions from "firebase-functions" admin. ...

Ways to customize the OverridableComponent interface within Material-UI

Is there a way to effectively use the Container component with styled-components incorporating ContainerProps, while still being able to pass the component prop that belongs to the OverridableComponent interface? Currently, I am encountering an error when ...

Is it advisable to include auto-generated files in an npm package upon publication?

I have a TypeScript NPM package where my build process compiles all *.ts files into myLib.d.ts, myLib.js, and myLib.js.map. In order for my NPM package to function properly, it requires the src/*.ts files as well as the auto-generated myLib.* files. Howe ...

Send users to the login page if they are not authenticated

Why is my middleware crashing after redirecting to the login page? import type { NextRequest } from "next/server"; import { NextResponse } from "next/server"; // To avoid crashing, this function can be marked as `async` if using `await ...

What should be the datatype of props in a TypeScript functional HOC?

My expertise lies in creating functional HOCs to seamlessly integrate queries into components, catering to both functional and class-based components. Here is the code snippet I recently developed: const LISTS_QUERY = gql` query List { list { ...

Navigating with hashtags in Angular2 and anchors does not change the page position

I recently came across a helpful post that showed me how to append a fragment to the URL. Angular2 Routing with Hashtag to page anchor Although the fragment is successfully added, I'm encountering an issue where the page does not scroll to the speci ...

MikroORM - Conditional join without foreign key constraints on the ID

I came across a rather peculiar database schema that includes a jsonb field with userId and userType attributes, along with two different user tables for distinct user types. The selection of the table to join based on the userType is crucial. Although I ...

Tips for implementing a multi-layered accumulation system with the reduce function

Consider the following scenario: const elements = [ { fieldA: true }, { fieldB: true }, { fieldA: true, fieldB: true }, { fieldB: true }, { fieldB: true }, ]; const [withFieldA, withoutFieldA] = elements.reduce( (acc, entry) => ...

Issue: The 'typeOf' function is not exported by the index.js file in the node_modules eact-is folder, which is causing an import error in the styled-components.browser.esm.js file in the node_modulesstyled

Every time I attempt to start running, there are issues with breaks in npm start (microbundle-crl --no-compress --format modern,cjs) I have attempted deleting node_modules and package-lock.json, then running npm i again but it hasn't resolved the pro ...

What is causing the issue where Multiple file selection does not work when using the multiple attribute

I am having issues with uploading multiple files on my website. I have created an input field with the attribute multiple, but for some reason, I am unable to select multiple files at once. app.html <input type="file" (change)="onChange($event)" req ...