"Loop through an array using forEach leads to a subscription that

I am a beginner in Angular and struggling to understand how async functions work. I have written the following code, but I am encountering an error:

GET https://localhost:44353/api/ecams/id/undefined 400
and
["The value 'undefined' is not valid."]
. It seems like the server response is not quick enough to proceed with the next instructions. Can someone guide me on the right approach?

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Exam } from '../_models/exam';
import { IndividualSession } from '../_models/individual-session';
import { IndividualSessionData } from '../_models/individual-session-data';
import { Session } from '../_models/session';
import { User } from '../_models/user';
import { AccountService } from '../_services/account.service';
import { ExamsService } from '../_services/exams.service';
import { IndividualSessionService } from '../_services/individual-session.service';
import { SessionService } from '../_services/session.service';
import { UsersService } from '../_services/users.service';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
  currentUser$: Observable<User>;
  user: User;
  userId: number;
  individualSessionsData: IndividualSessionData[] = [];
  
  tempIndividualSessionData: IndividualSessionData = {} as IndividualSessionData;

  constructor(private accountService: AccountService,
    private individualSessionService: IndividualSessionService,
    private userService: UsersService,
    private examService: ExamsService,
    private sessionService: SessionService) {
       this.tempIndividualSessionData.exam = {} as Exam;
       this.tempIndividualSessionData.individualSession = new IndividualSession();
       this.tempIndividualSessionData.session = {} as Session;
       this.getCurrentUserData();
      }

  ngOnInit(): void {

  }

  onRowClick(){
    
  }

  logout() {
    this.accountService.logout();
  }

  private getCurrentUserData() {
    this.currentUser$ = this.accountService.currentUser$;
    this.currentUser$.subscribe(user => {
      if (!!user) {
        this.user = user;
        this.loadUser(this.user.email);
      }
    });
  }

  loadUser(email: string) {
    this.userService.getUser(email).subscribe(user => {
      if(!!user) {
        this.user = user;
        this.loadId(this.user.email);
      }
    })
  }

  loadId(email: string) {
    this.userService.getId(email).subscribe(id => {
      if(!!id) {
        this.userId = id;
        this.loadIndividualSessions(this.userId);
      }
    })
  }

  loadIndividualSessions(id: number) {
    this.individualSessionService.getIndividualSessions(id).subscribe(sessions => {
      if(!!sessions) {
        sessions.forEach(session => {
          this.tempIndividualSessionData.individualSession = session;
          this.loadSession(session.sessionId);
        });
      }
    })
  }

  loadSession(id: number) {
    this.sessionService.getSession(id).subscribe(session => {
      if(!!session) {
        this.tempIndividualSessionData.session = session;
        this.loadExam(session.examId);
      }
    })
  }

  loadExam(id: number) {
    this.examService.getExamById(id).subscribe(exam => {
      if(!!exam) {
        this.tempIndividualSessionData.exam = exam;
        this.individualSessionsData.push(this.tempIndividualSessionData);
      }
    })
  }
}

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { Exam } from '../_models/exam';
import { Question } from '../_models/question';

@Injectable({
  providedIn: 'root'
})
export class ExamsService {
  baseUrl = environment.apiUrl;
  currentExam: Exam;
  answeredQuestions: Question[];
  correctAnswers: number[];
  currentMark: number;

  constructor(private http: HttpClient) { }

  getExams() {
    return this.http.get<Exam[]>(this.baseUrl + 'exams');
  }

  getExam(title: string){
    return this.http.get<Exam>(this.baseUrl + 'exams/title/' + title); 
  }

   getExamById(id: number){
     return this.http.get<Exam>(this.baseUrl + 'exams/id/' + id); 
   }

}

If anyone can provide assistance, it would be greatly appreciated. Happy coding!

Answer №1

When you encounter the HTTP code 400 error, it indicates that your request is incorrect:

https://localhost:44353/api/ecams/id/undefined

Here are three key points to note:

  1. A simple typo: It should say "exams" instead of "ecams"
  2. The presence of "undefined" suggests that the value you are trying to append is indeed undefined.
  3. If you do not have control over the API and it follows REST principles, the URL should probably read as follows:
    https://localhost:44353/api/exams/1/something
  4. It's advisable to review your method parameters for any instances where they may be undefined or null.

It appears that at least once, session.examId in loadExam() is undefined. Consider updating your code as shown below:


loadExam(id: number) {
    if (id){
        this.examService.getExamById(id).subscribe(exam => {
          if(exam) {
            this.tempIndividualSessionData.exam = exam;
            this.individualSessionsData.push(this.tempIndividualSessionData);
          }
        });
    } else {
        console.error("Exam id is null or undefined.");
    }
}

You can insert a line such as console.log(session); within the sessions.forEach() call to identify any sessions lacking an examId. Additionally, utilize the browser's developer tools to monitor network activity during API requests. Are the requests successful? If yes, make sure you are capturing the results correctly. If not, revisit the parameters you are attempting to send.

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

What could be the reason for the absence of a TypeScript error in this situation?

Why is it that the code below (inside an arbitrary Class) does not show a TypeScript error in VSCode as expected? protected someMethod (someArg?: boolean) { this.doSomething(someArg) } protected doSomething (mustBePassedBoolean: boolean) { /* ... * ...

What is the best way to enable the acceptance of a null value during the validation process of an optional

Currently, I am in the process of assembling a sandwich. Whenever all the necessary details are provided to Nest, everything operates smoothly and flawlessly. However, my predicament arises when attempting to assign null (empty string) to an enum, resultin ...

Having difficulty testing an Angular/NGXS action that triggers after an unsuccessful API request

Struggling with writing tests for an NGXS action that calls an http request? Want to add tests for both successful and failed requests? Here is the code for my Action: @Action(SearchChuckNorrisJokes) searchChuckNorrisJokes({ getState, setState }: StateCo ...

Issue with <BrowserRouter>: TS2769: No suitable overload for this call available

I encountered this error and have been unable to find a solution online. As a beginner in typescript, I am struggling to resolve it. The project was originally in JavaScript and is now being migrated to TypeScript using ts-migrate. I am currently fixing er ...

What's causing this issue in Angular?

In this scenario, there is a parent component and a child component communicating with each other. The parent component passes a method to the child component, which the child component then calls and sends its own instance back to the parent. However, wh ...

Using Apache to rewrite wildcard subdomains for an Angular application

I am currently facing a challenge with my Angular app that needs to be set up under subdomains for multi-tenant support. Each subdomain represents a different tenant within the application. At present, I have an .htaccess configuration that successfully lo ...

What are the main challenges in resolving dependencies and implementing best practices when it comes to updating an outdated Angular NodeJS

After several months away, I am now faced with the challenge of updating and maintaining an out-of-date angular project. Seeking advice from experienced developers on how to tackle this situation. Previously, I used NPM update or upgrade commands to keep ...

Ag-grid hack: Changing cell color in a row without utilizing the Cell Styles property within column definitions

[{ "uniqueIdentifier": "12345", "identifier": "UJHU", "latitude": 33.68131385650486, "longitude": -83.36814721580595, "cycle": "1" "speedLimit" ...

Experiencing code coverage challenges in Angular 8 relating to function properties

Looking for suggestions on how to create a unit test case in Jasmine to address the code coverage problem. Any ideas? ...

Updating the value of the chosen drop down option upon selection

I currently have a Material UI dropdown menu implemented in my project. My goal is to use the selected option from the drop down menu for future search functionality. How can I utilize onChange() to store the selected option effectively? At the moment, I ...

Learn how to define an object with string keys and MUI SX prop types as values when typing in programming

I want to create a comprehensive collection of all MUI(v5) sx properties outside of the component. Here is an example: const styles = { // The way to declare this variable? sectionOne: { // What type should be assigned here for SXProps<Theme>? } ...

How can you implement multiple validators on a single control in Angular 2?

I've been working on a form using Angular2 and I've implemented two custom validators for the email address field. The initial validator checks for valid email format, while the second (which is asynchronous) checks if the email address already ...

A guide on capturing the text content of the error message from the <mat-error> element with Protractor

I have encountered an element that is giving me trouble in retrieving the error message text into a variable. <mat-error _ngcontent-c16="" class="mat-error ng-star-inserted" id="error-email-required" role="alert" ...

Ways to avoid route change triggered by an asynchronous function

Within my Next.js application, I have a function for uploading files that includes the then and catch functions. export const uploadDocument = async (url: UploadURLs, file: File) => { const formData = new FormData(); formData.append("file" ...

Setting up a variable with a changing value

In a very specific scenario, the body of type varies based on the length_type attribute (as illustrated in the example). enum LengthTypeEnum { SELECT = 'SELECT', STATIC = 'STATIC', CONDITION = 'CONDITION', PERIOD = ...

angular2 ngFor is not functioning properly

I'm having an issue where I cannot get textboxes to appear whenever a user clicks a button. I am attempting to achieve this using ngFor, but for some reason, the ngFor is not iterating as expected. Even after trying to change the array reference with ...

TypeScript's type 'T' has the potential to be instantiated with any type, even if it is not directly related to 'number'

Let's say we have a function that takes a value (for example, number) and a callback function that maps that value to another value. The function simply applies the provided callback: function mapNumber<T>(value: number, mapfn: (value: number) = ...

Issue with locating module in Visual Studio 2015 when using Angular5 and TypeScript version TS2307

I'm currently attempting to integrate Angular in Visual Studio 2015 update 3, but encountering the following error: TS2307 cannot find module '../node_modules/@angular/core'. The error is shown in the image linked here. Can anyone help me fi ...

CSS styles from Angular 2 components spilling outside of their boundaries

Check out the Plunker where I'm facing an issue. "If you comment out the styles in the ThirdComponent, you can see it affecting the parent and sibling components' styles." – adriancarriger (Special thanks to Adrian) Within my component, I am i ...

Passing a response from a combination of asynchronous and synchronous functions in a provider script to an Express server

Forgive me for bringing up this issue - I know there is an abundance of information on async functions available, but despite trying various approaches, I am unable to find a solution... To provide some context, let me describe the setup of my program. It ...