What is the reason for the component property being valued within the subscribe body when it is not defined outside of it?

I am currently facing an issue with retrieving data from a SQL server table using http.get within the constructor of an Angular component 5. While I am able to assign the retrieved data to a component property inside the subscribe method, the value becomes "undefined" when I try to access it later on. Here is the code snippet and the output I am encountering:

topic.service.ts

import { Injectable, Inject, Input, OnChanges, SimpleChanges } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { AuthService } from '../auth.service';

@Injectable()
export class TopicService {
  topics: Topic[];
  name: string;

  constructor(private http: HttpClient,
    @Inject('BASE_URL') private baseUrl: string,
    private router: Router,
    public auth: AuthService) {    

    http.get<Topic[]>(baseUrl + 'api/Topic/List').subscribe(result => {
      this.topics = result;
      console.log(this.topics);         // It has a value
    }, error => console.error(error));

console.log(this.topics);     // It no longer has a value - it is undefined

  }

}

Displaying "Chrome DevTools":

enter image description here

I am puzzled as to why I have the data but cannot utilize it. Any assistance in resolving this issue would be greatly appreciated.

Answer №1

It is no longer cherished - it is indeterminate

Upon examining your image, it appears to be not yet established/"cherished". This can be confirmed by the fact that undefined is displayed in the console prior to the array.

Since get is asynchronous, the callback function in subscribe has not been executed yet, resulting in this behavior.

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

In a Custom Next.js App component, React props do not cascade down

I recently developed a custom next.js App component as a class with the purpose of overriding the componentDidMount function to initialize Google Analytics. class MyApp extends App { async componentDidMount(): Promise<void> { await initia ...

Dynamic Material UI Timeline

I am facing a challenge with making the Timeline in Material UI responsive for the first time. Currently, I have it set to align 'alternate', but I want it to switch to align 'left' when viewed on mobile or certain screen widths. I have ...

Tips for adjusting the dimensions of a map within the app.component.html

Within the code snippet below, my aim is to adjust the width and height of the map using the style tag shown here: <style> #map3 .map { width: 100%; height:90px; } </style> Despite trying various values for width an ...

Binding data with non-nested components

My dilemma involves two components - one with checkboxes and the other with a table. These components are not nested within each other. I want to manipulate certain classes in the table columns when a checkbox is unchecked. Can anyone suggest the most ef ...

Typescript encounters difficulty locating the Express module

My venture into creating my debut NodeJS application has hit a roadblock. Following advice from multiple blogs, I have been attempting to build my first nodejs app in typescript by following the steps below: npm install -g express-generator npm install - ...

Tips on showcasing Java map information obtained from the backend on an Angular/Typescript interface

I have a 'detailsMap : any' variable from the backend that contains multiple rows in the format (key1,key2). I need to display this data in the UI using TypeScript/Angular2. Please advise on how I can achieve this. key1 : { Name:'ABC' , ...

Presenting two arrays simultaneously creates angular duplicates

Encountering an issue while trying to display two arrays containing channel information: List of channels List of subscriptions that users have opted for. channels = [ { "id": 1, "name": "arte", "service&q ...

Run the code before the http observable initiates the network request

Is there a way to write code that executes before an Angular HTTP client observable makes a network call, but after the function is called? The following code snippet shows an example of an Angular HTTP service call: this.geocodeApi.getAddressSuggestions( ...

Two unnamed objects cannot be combined using the AsyncPipe

Currently, I am looking to implement an autocomplete feature using Angular Material in Angular 8. Below is a snippet of the code used in the TypeScript file: @Input() admins: User[]; userGroupOptions: Observable<User[]>; filterFormFG: FormGrou ...

TypeScript type that specifically mandates the properties of an object

Let's consider the following scenario: const myObj = { foo: 'cat', bar: 'dog', baz: 'bird' } as const; type MyValue = 'fish' | 'bear' | 'cow'; const myValueMap: Record<string, MyValue> ...

Dealing with checkbox changes in Angular 2

I have a checkbox that is initially checked, and I want to use the (change) event on it. After being clicked, I want to clear the input text for "Activation key". When re-checked, I want to generate a GUID and add it back to the input field. How can I dete ...

Creating a dynamic HTML component with Angular

I am tasked with developing two separate themes for an angular application. These themes should be loaded based on a property retrieved from an API call. I plan to create two HTML files that will share the same .ts code, since the core functionality will n ...

Exploring the mechanics behind ES6 Map shims

From what I've gathered from the documentation (here and here), it seems that having a reference to the memory address is necessary for the operation to work: const foo = {}; const map = new Map(); map.set(foo,'123'); // This action requi ...

What could be the reason my RxJS Observable chain does not run again when new emissions are made?

Currently, I am facing a unique challenge while working with RxJS in an Angular service. The issue revolves around two observable chains designed to enhance a stream of notifications with user data. One chain functions correctly, allowing for multiple trig ...

The npm warning indicates that the file node_modules/.staging/typescript-8be04997/lib/zh-CN/diagnosticMessages.generated.json does not exist due to an ENOENT error

I am currently in the process of running npm install on a Linux machine where I do not have sudo access. Unfortunately, I have a machine-specific package.json and package-lock.json that cannot be changed. However, I encountered some errors during the insta ...

Avoiding data type conversion in JavaScript/TypeScript

Currently delving into the world of JavaScript, I come from a background of working with statically typed languages. Naturally, I opted to dive into TypeScript instead of starting directly with JS. While TypeScript is great and addresses many issues presen ...

The 'property' is not found within the type '{ my_function(): void; }'

I am just starting out with TypeScript and VueJS. Currently, I am pondering the best approach for setting the type of a JSON key that should start off as null. <script lang="ts"> import Vue from 'vue'; export default Vue. ...

Angular 2 - Component's Off-click Feature Falters

Achieving a desired effect using Angular 2, I have implemented a component with a small popup <div>. The popup is dismissed when the user clicks anywhere on the document except for the popup itself. To achieve this functionality, I utilize HostListen ...

Can the Okta Sign-In Widget be tailored to incorporate Angular Material elements?

I’ve recently integrated the @okta/okta-signin-widget into my Angular SPA, and it displays as follows: <span> <input id="okta-signin-username" type="text"> </span> My Angular SPA is styled using the Angular Mate ...

Customizable JSX Attributes for Your TSX/JSX Application

Currently, I am in the process of converting my React project from JavaScript to TypeScript. One challenge I encountered is that TSX React assumes all properties defined in a functional component are mandatory props. // ComponentA.tsx class ComponentA ext ...