Encountering the issue of receiving "undefined" when utilizing the http .get() method for the first time in Angular 2

When working in Angular, I am attempting to extract data from an endpoint. Below is the service code:

export class VideosService {
  result;
  constructor(private http: Http, public router: Router) { }

  getVideos() {
    this.http.get('http://localhost:3000/videos?sessionId=' + localStorage.getItem('sessionId'))
        .map(response => response.json())
        .subscribe(result => this.result = result);
        localStorage.setItem('videos', this.result);
        console.log(localStorage);
  }

Everything seems to work fine except on the first try. On the initial attempt, I receive "undefined" as the result but subsequent attempts return the correct object.

Any advice on what mistake I might be making? Thanks!

Answer №1

Regarding your code snippet:

.subscribe(result => this.result = result);
localStorage.setItem('data', this.result);

The line

localStorage.setItem('data', this.result);
is being executed prior to the
.subscribe(result => this.result = result);
.

Solution

You can address this issue by delving into asynchronous programming in JavaScript or alternatively, try:

.subscribe(result => {this.result = result;   localStorage.setItem('data', this.result);});

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

Validation errors in the realm of Zod

Below is my code using Next.js 14 with TypeScript, React Hook Form, and Zod for validation. The issue arises when trying to display an error message for an empty form: import React from "react"; import category from "@/components/expenses/ca ...

Struggling to translate JavaScript code into Typescript

Currently in the process of converting my JavaScript code to Typescript, and encountering an error while working on the routes page stating Binding element 'allowedRoles' implicitly has an 'any' type. ProtectedRoutes.tsx const Protecte ...

Pay attention to the input field once the hidden attribute is toggled off

In attempting to shift my attention to the input element following a click on the edit button, I designed the code below. The purpose of the edit is to change the hidden attribute to false. Here's what I attempted: editMyLink(i, currentState) { ...

Add a tooltip to the mat-tab title

I have been attempting to implement tooltips on tabs using matTooltip, but I can't seem to get it working. Despite referencing the documentation and searching through Stack Overflow questions, I am unable to identify the root cause of this issue. Cou ...

What steps are required to transition an Angular application developed without the Angular CLI into an Angular CLI project?

I've created an Angular app using tools like NPM (without utilizing the Angular CLI). What would be the most efficient way to transition this project into the CLI project structure? I want to have the ability to utilize commands like ng serve. ...

Utilize TypeScript enum keys to generate a new enum efficiently

I am in need of two Typescript enums as shown below: export enum OrientationAsNumber { PORTRAIT, SQUARE, LANDSCAPE } export enum OrientationAsString { PORTRAIT = 'portrait', SQUARE = 'square', LANDSCAPE = 'landscape&ap ...

Angular 2 - resolving the access control allow origin header issue

My project utilizes Spring on the back-end and Angular2 on the front-end. In the webapp folder of my Spring project, there is a JSON file that I am attempting to access from Angular. I can successfully access the file by directly typing "http://localhost: ...

Unlocking the power of variables in Next.js inline sass styles

Is there a way to utilize SASS variables in inline styles? export default function (): JSX.Element { return ( <MainLayout title={title} robots={false}> <nav> <a href="href">Title</a> ...

Extracting individual parameters from a specific URL in Angular 9

Imagine we have various types of urls: [1] /home/users/:id [2] /home/users/:id/posts/:id [3] /home/users/:id/posts/:id/comments/:id I am looking to create a method called parseUrl(url: string): any[] {} that can take a url as input and provide an array ...

What is the process for transitioning global reusable types to package types within turborepo?

When creating an app within the apps folder, a global.d.ts file is required with specific types defined like this: interface Window{ analytics: any; } This file should be designed to be reusable and placed in the packages/types directory for easy acce ...

What could be causing the issue with Vite build and npm serve not functioning together?

After shifting from CRA to VITE, I am encountering a problem with serving my app. I successfully build my app using vite build. and can serve it using Vite serve without any issues. However, I want to use npm's serve command. Whenever I run vite bui ...

Issue with variable not being populated by Observable

Although my observable is sending back the correct object, I am facing an issue where the data is not being stored against a local variable. import { Component, OnInit, OnDestroy } from '@angular/core'; import { LookupListsService } from '.. ...

What is the process for obtaining an AccessToken from LinkedIn's API for Access Token retrieval?

We have successfully implemented the LinkedIn login API to generate authorization code and obtain access tokens through the browser. Click here for image description However, we are looking to transition this functionality to an ajax or HTTP call. While w ...

I am encountering a problem with my component as the Angular Directive is missing

Recently, I incorporated a customized directive into my Angular app to allow file uploads via drag and drop. However, I encountered an issue where the command line kept throwing an error stating that my function does not exist within my component. Propert ...

Determine whether one class is a parent class of another class

I'm working with an array of classes (not objects) and I need to add new classes to the array only if a subclass is not already present. However, the current code is unable to achieve this since these are not initialized objects. import {A} from &apo ...

Running Angular/Rxjs store (ngrx) calls synchronously

After fetching 2 items from my store using ngrx, I need both requests to complete before taking further action. Here's an example of what I'm trying to achieve: const item1$: Observable<Item> = this._store$.select( ItemStoreSelectors.sele ...

Best practices for transitioning a project from TypeScript 3 to TypeScript 4?

I am looking to upgrade my large monorepo, which was built using lerna, React, and TypeScript 3.7 around 2-3 years ago. My goal is to update it to TypeScript 4.8. Are there any tools available that can help me analyze and identify potential breaking chan ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

Guide to transforming a TaskOption into a TaskEither with fp-ts

I have a method that can locate an item in the database and retrieve a TaskOption: find: (key: SchemaInfo) => TO.TaskOption<Schema> and another method to store it: register: (schema: Schema) => TE.TaskEither<Error, void> Within my regis ...

having difficulty deactivating matInput within angular form

I am facing an issue with a form where I need to disable one of the inputs based on a certain condition. <mat-form-field> <input matInput formControlName="domain" [disabled]="!is_staff && recipients[selectedIndex].verified"> </m ...