No data found on Angular TypeScript page with an empty array

Incorporated a function called 'getQuestionsWithInterviewId' to populate my 'Questions' string, but it appears empty when I attempt to call it within the ngOnInit and ngAfterContentInit methods and log the result in the console.

import { Component, OnInit } from '@angular/core';
import { QuestionService } from '../_services/question.service';
import { Question } from '../_models/model';

@Component({
   selector: 'app-interview',
   templateUrl: './interview.component.html'
 })

 export class InterviewComponent implements OnInit {

 questions: Question[]=[];

 constructor(private questionService: QuestionService) {

 }

 ngOnInit(): void {
 }

 ngAfterContentInit() {
    this.getQuestionsWithInterviewId(1);
    console.log(this.questions);

    $(".tab-wizard").steps({
      headerTag: "h6",
      bodyTag: "section",
      transitionEffect: "fade",
      titleTemplate: '<span class="step">#index#</span> #title#',
      labels: {
        finish: "end"
      },
      onFinished: function (event, currentIndex) {
        alert("end");
      }
    });

  }

  getQuestionsWithInterviewId(interviewId: number) {
    this.questionService.getQuestionsWithInterviewId(interviewId).subscribe(a => {
    this.questions = a;
  },
  error => {
    console.log(error);
  });
 }

}

https://i.sstatic.net/TmTMB.png

However, on the component.html page, when I utilize the 'questions' array, the results are visible.

https://i.sstatic.net/FIdny.png

https://i.sstatic.net/RuqUR.png

If I execute the console.log operation within the 'getQuestionsWithInterviewId' function, the results are displayed correctly.

getQuestionsWithInterviewId(interviewId: number) {
this.questionService.getQuestionsWithInterviewId(interviewId).subscribe(a => {
  this.questions = a;
  console.log(this.questions);
},
  error => {
    console.log(error);
  });
 }

https://i.sstatic.net/emAiZ.png

question.service.ts page;

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Question } from '../_models/model';

@Injectable({
  providedIn: 'root'
})
export class QuestionService {

  baseUrl: string = 'https://localhost:44388/api/questions/';

  constructor(private http: HttpClient) {

  }

  getQuestionsWithInterviewId(interviewId: number): Observable<Question[]> {
    return this.http.get<Question[]>(this.baseUrl + 
"GetQuestionsWithInterviewId/" + interviewId);
  }


}

Answer №1

Avoid creating an additional method called "getQuestionsWithInterviewId" in your component - instead, call the service directly. It is suggested to do this in the ngOnInit lifecycle hook, shown below:

ngOnInit() {   
    this.questionService.getQuestionsWithInterviewId(1).subscribe(response => {
      this.questions = response;
      console.log(this.questions);
    },
    error => {
        console.log(error);
      });
    }
    
    $(".tab-wizard").steps({
        headerTag: "h6",
        bodyTag: "section",
        transitionEffect: "fade",
        titleTemplate: '<span class="step">#index#</span> #title#',
        labels: {
          finish: "end"
        },
        onFinished: function (event, currentIndex) {
          alert("end");
        }
     });
}

Answer №2

The reason behind this behavior is that the function getQuestionsWithInterviewId utilizes an observable from the questionService.

The variable questions gets populated when you set it equal to this.questions = a. This assignment occurs when the subscription is triggered. Subscriptions are only fired once the entire call stack is empty, typically right after the execution of ngAfterContentInit.

If you need to manipulate data from the subscription, you should perform those actions within the subscribe callback function.

Additional Information

ngOnInit() {   
    this.questionService.getQuestionsWithInterviewId(1).subscribe(a => {
      this.questions = a;
      // this console log is useful for debugging
      console.log(this.questions);
      // you can apply any modifications to the questions here
    },
}

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

Tips for improving DOMContentLoaded performance with Angular2

Currently, I am in the process of converting a JQuery template to Angular 2, specifically a Dashboard-like template. This website has numerous popups, each containing multiple tabs, so I decided to separate each popup into different components to keep the ...

`"Error: posts.map is not a function" - What steps can be taken to resolve this issue?`

While working on fetching data from my local Drupal instance in React JS, I encountered a situation where I needed to pass the data from Drupal using the JSON API module which sends the data in JSON format. You can view the JSON API data in the following i ...

Is one round the limit for my JavaScript image slider?

After studying the JavaScript Chapter on W3Schools, I attempted to create an image slider. Initially, everything worked perfectly for the first cycle. For instance, when I clicked the next button, the slides continued to slide until the end of the slidesho ...

In Node.js, the mongodb+srv URI does not support including a port number

Currently, I am working on a project in nodejs using express js. I have encountered the following error: MongoDB connection error: MongoParseError: MongoDB+srv URI cannot contain a port number. In my "MongoDB Atlas" dashboard, I have obtained my "connecti ...

Developing Attributes in JSON

Greetings stackOverflow Community, I'm struggling a bit with creating JSON objects. I have code snippet that is meant to populate a list called members with names, and then add a property to each of those names. Here is the specific snippet in questi ...

Angular's onreadystatechange event is triggered when the state

Hey there, I'm new to Angular and had a question. Is it possible to use the $http service in Angular to trigger a function whenever there is any change in the ready state/status, not just for success or failure? If so, what would be the equivalent ang ...

I made a request using the post type fetch to submit data to this form, but unfortunately, the server-side response returned

I encountered an issue where after sending the post type fetch to this form, I received 'undefined' on the server side. Here's the code snippet for my fetch request: const { text, id } = Data; fetch('http://localhost:3001/add' ...

Can we link together two separate ngfor loops in any manner?

<div class="gl-w-100 gl-md-w-auto gl-po-rel list"> <div class="signin_wrpr gl-w-100 gl-po-rel gl-d-flex gl-fd-column gl-bg-white gl-lg-w-auto gl-md-w-auto gl-h-100 gl-md-ta-c"> <div class="head g ...

parsing and building a sophisticated JSON object

i have a complex array structure as shown below, array=[ { 'mm': '1', exp: 'exp1' }, { 'mm': '2', exp: 'exp2' }, { 'mm': [ '1', '3', '7' ], exp: &ap ...

Angular 2: Issue with directive not triggering set function

I am puzzled as to why the alert() function within the setter of my directive is only triggered once when the value of the input element it is applied to changes. It works on the initial page load but not subsequently. I was expecting that since the value ...

The air-datepicker functionality seems to be malfunctioning within an Angular 4 environment

When using static HTML, it's quite simple to integrate Air Datepicker by following the documentation available at : <html> <head> <link href="dist/css/datepicker.min.css" rel="stylesheet" type="text/css"> <scr ...

Tips for accessing the PR number in a Node.js GitHub Probot listening for the `pull_request` event

I've recently developed a GitHub probot application using nodejs and typescript. Currently, I have set up an event listener for the pull_request event. How can I extract the pr_number from the context object within the probot? The snippet below is fr ...

In what part of my code should I integrate the .sort() method?

I am working on rendering a list of items in alphabetical order to the browser. I have previous experience using .sort() in other scenarios, but I am unsure about where to place it in this particular situation. In my current code, I initially placed the . ...

Trigger the fire event on .click() except when text is being selected

I am currently working on a chat box project and I want the input field within the message area to automatically get focused when the user clicks anywhere in the chat box. However, I don't want this functionality to interfere with text selection for c ...

What is the appropriate method to send a single observable problem to two Observable<boolean>?

Two functions are at play here: this.baseAuthentification.canActivate(route, state) and this.haveDroits(). Both of them return observables. I am looking to return an observable in case this.baseAuthentification.canActivate(route, state) returns false. If ...

Delete the initial instance of a specific element with JavaScript or Lodash

I am working with an array that looks like this - ["a", "a", "b", "c", "d", "e"] My goal is to filter this array in a way that removes only the first occurrence of each element. Based on the exa ...

"Alert: The ToastData is nowhere to be found in

In my previous Angular 5 application, I was using ng2-Toasty for displaying toasts. However, since ng2-Toasty does not support Angular 8, I am now trying to switch to ngx-toastr. Upon implementation, I noticed that ngx-toastr does not have an equivalent o ...

"Organizing a menu in JSON format based on alphabetical

After following this guidance, I successfully created a JSON menu. However, the items are currently sorted by ID and I am in need of sorting them alphabetically. I am unsure about whether using array.sort(); would be applicable in this scenario. Check out ...

Unlock the secrets of programming with the must-have guide to mastering variables

As a newcomer to the world of programming, I may be jumping ahead by asking this question too quickly. While reading a book, I came across something that confused me. Why is it necessary to create a variable for the password box element? Wouldn't the ...

How to modify a single entry in a MongoDB database with the help of Node.js and

How do I update a specific record by _id in a MongoDB collection? A recent UPDATE: After making some changes to the code, I now encounter a 500 internal server error. Any suggestions on resolving this issue would be greatly appreciated. "_id ...