Could someone please explain why the function getTasks() is showing up as undefined?

After successfully retrieving tasks from the API and confirming that the data is accurate, I encountered an issue when trying to log it in the console as it returned undefined.

Below is my code:

tasksEvents: Task[];


getTasks() {
    this._taskService.getTasks()
    .subscribe(
        res => { this.tasksEvents = res },
        err => console.error(err)
    )
}

ngOnInit(): void {
    this.getTasks();
    console.log(this.getTasks(); <------ Undefined
}

Although the data retrieval is working fine, I am looking for ways to further utilize the getTasks() function.

Here is the relevant snippet from task.service.ts:

taskUrl = 'http://127.0.0.1:8000/api/tasks';

getTasks() {
    return this._http.get<Task[]>(this.taskUrl);
}

Answer №1

When using an asynchronous function like <code>getTasks()
, you must implement mechanisms such as subscribe() or other RxJS operators like tap/do to access the emitted values. To improve your code, adjust getTasks() to return an observable (eliminate subscribe()) and utilize subscribe() in ngOnInit() to assign the value to the class property and log it if necessary:

tasksEvents: Task[];

getTasks() {
  return this._taskService.getTasks();
}

ngOnInit(): void {
  this.getTasks().subscribe(res => {
    this.tasksEvents = res;
    console.log(res);
    console.log(this.tasksEvents);
  });
}

This modification should provide clarity!

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

Error message stating that NgxMatDatepickerBase provider is not found in ngx-mat-datepicker

I encountered an error while trying to add multiple date time pickers (inputs) in my Angular web application using @angular-material-components/datetime-picker. core.mjs:10194 ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule ...

Ways to alter the color of individual pseudo elements using a CSS loop

While working on creating a typewriter animation effect for my website using only CSS that I discovered through some online research, a question popped into my mind - is it possible to set different colors for each text in the animation? I have included t ...

Containerizing Next.js with TypeScript

Attempting to create a Docker Image of my Nextjs frontend (React) application for production, but encountering issues with TypeScript integration. Here is the Dockerfile: FROM node:14-alpine3.14 as deps RUN apk add --no-cache tini ENTRYPOINT ["/sbin ...

Utilizing Array Notation in Typescript to Retrieve Elements from Class

In my programming project, I am working with two classes: Candles and Candle. The Candles class includes a property called list, which is an array containing instances of the Candle class. class Candles { public list: Array<Candle>; } class Candl ...

What is the best way for the frontend to access the information of the user currently logged in?

When users authenticate on my endpoint by providing their username and password, a JWT is returned if the credentials are correct. Now, I want to be able to show user-specific information after they log in. How can the frontend determine which user is cur ...

Even with the presence of FormsModule, ngModel is still unrecognized as a property

I am currently experiencing a unique issue with my Angular CLI version 8.0.29. The problem initially arose in one project, prompting me to create a new project using the CLI to troubleshoot the issue during boilerplate creation. The specific problem invol ...

A button created in SVG dynamically adjusts its position when the highcharts are resized

Utilizing the highcharts library to display a pie chart. Check out the Stackblitz demo here In order to incorporate two additional buttons for currency and percent toggle, I have employed the SVG Renderer to position and align these buttons below the cen ...

Listening to events on the iterative variable of NgFor directive in Angular 2

Angular2 has been my latest exploration in solving a unique data binding challenge. In my UI, I've presented a javascript array of objects like a database recordset in an HTML table. Each row contains menus and inputs allowing users to modify the rec ...

Pass a React component as a required prop in Typescript when certain props are necessary

I am currently working on a project where I need to create a custom TreeView component using React and Typescript. My goal is to have the ability to inject a template for each TreeNode in order to render them dynamically. My main challenge right now is fi ...

Troubleshooting problem with iPhone X responsiveness

Struggling with responsive issues on iPhone X. Issue is only appearing on actual device. Any tips for fixing this? I'm facing an issue where the website looks good and responsive on all devices in Chrome's responsive view. But when I access it th ...

Using Angular to display the initially selected option value in a select dropdown menu

Struggling to set the default selected option in a select input using Angular. I've tried several solutions with no success. It's baffling why this is proving so difficult for me. Any assistance would be greatly appreciated, thank you. The selec ...

What is the best way to create a new instance for each incoming HTTP request in NestJS?

While working with my API, I encountered an issue where the classes were not being destroyed after receiving a response. Currently, I am using nestJS, but when I tested nodeJS + expressJS, I also faced the same problem. The code I am using is as follows: ...

What is the reason behind Collection.bulkwrite() only writing a single document to the MongoDB database?

I have utilized ag-grid to create this grid, and my objective is to bulkwrite its data into my MongoDB database by clicking on the saveInformation button. https://i.sstatic.net/bbMN4.png app.component.ts saveInformation() { console.log('actio ...

Steps to Turn Off TSLint Alert for Dep Import Concerns

Encountering a warning while compiling an angular universal app: Warning: Entry point 'my-module' includes deep imports from '/src/app/mocks/myModule.ts'. Although not necessarily problematic, it may lead to out of order compilatio ...

Is there a way to utilize Typescript enum types for conditional type checking?

I'm working with restful services that accept enum values as either numbers or strings, but always return the values as numbers. Is there a way to handle this in TypeScript? Here's my attempt at it, although it's not syntactically correct: ...

Finding comfort through NodeJS without relying on immediate success

My current challenge involves setting up Solace, a queuing system, to establish a session and then send a message on that session. However, instead of completing the session creation process, it seems to ignore all the event handlers I've registered a ...

Steps for injecting a @liaoliaots/nestjs-redis redis connection into a global guard constructor

Hello everyone, I am currently exploring NestJS and running into some issues with the @liaoliaots/nestjs-redis package. One specific example involves a guard that I have created with the following constructor: import { InjectRedis } from '@liaoliaots/ ...

Creating a way for a Google Maps overlay to refresh independently without affecting the rest of the page

Important to note that this question is tied to the one I posted here Within my HTML code, I am constructing an overlay for a Google Map using: <agm-map ngDraggable [latitude]="latitude" [longitude]="longitude" [zoom]="zoom" *ngIf="locations" (mapRead ...

Dayjs is failing to retrieve the current system time

Hey everyone, I'm facing an issue with using Dayjs() and format to retrieve the current time in a specific format while running my Cypress tests. Despite using the correct code, I keep getting an old timestamp as the output: const presentDateTime = da ...