Retrieve information from subscriber and store it in a local variable

Angular 6 Service

getProjectEpics(id: string): Observable<any> {
return this.http.get<any>(this.baseUrl + 'getEpics/' + id);
}

Component Angular 6

projectEpics=[];
getProjectEpics(id: string) {
this.epicService.getProjectEpics(this.id).subscribe(
  next => {
    console.log('RESPONSE', next);
    this.projectEpics = next[0].epics;
    console.log(this.projectEpics); // array has data
  },
  error => {
    this.alertify.error(error);
  }
);
console.log(this.projectEpics); // The array is empty at this log.
}

In my project using Angular 6, I have set up a service method called getProjectEpics which returns an observable of any type by making an API call. In the component, I am subscribing to this observable method from the service. When I receive the data from the API and service, I assign the data stored in the 'next' object to a local array named projectEpics. When I log this array inside the subscription block, it shows the expected data. However, when I log it outside the subscription block, the projectEpics array appears empty with no data.

Answer №1

One unique characteristic of observables is their asynchronous nature. In a single thread environment like Javascript, any asynchronous tasks are delegated to the surrounding environment (such as the Browser or NodeJS) to be executed in a separate thread. Here's how JavaScript handles these tasks:

  1. The main thread initiates a call to getProjectEpics()
  2. It then delegates the execution of this.epicService.getProjectEpics() and continues with other tasks
  3. The main thread proceeds to execute your final console.log() statement - even before the second step is completed

In the last console.log() statement, the array will be empty because it does not wait for the API call to finish.

If you want a more detailed explanation, you can check out this informative video.

Answer №2

When working with async calls, the scope/thread limits your access to variables. To communicate externally, consider utilizing a service, RxJS subjects, or other methods.

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

How is it possible for a TypeScript function to return something when its return type is void?

I find the book Learning JavaScript to be confusing. It delivers conflicting information regarding the use of void as a return type in functions. const foo = (s: string): void => { return 1; // ERROR } At first, it states that if a function has a re ...

What steps can I take to enhance the quality of my PDF files? Currently, I am utilizing Jspdf in conjunction with html

My current challenge involves generating a PDF file from my application. Although I am able to create a PDF, the quality is not up to par. When I download the PDF, I notice some discrepancies in text quality. While it's not terrible, it's also n ...

The <g> tag fails to properly render within the <svg> element in Firefox

When running an Angular 6 application with ES6-style D3js modules, there are some issues on Firefox (Chromium, Chrome, Safari, and IE Edge work fine). Below is a sample of pseudo code (full production code is available below): <svg width="500" height=" ...

Angular: controller's property has not been initialized

My small controller is responsible for binding a model to a UI and managing the UI popup using semantic principles (instructs semantic on when to display/hide the popup). export class MyController implements IController { popup: any | undefined onShow(con ...

Encountering an issue in Angular 8 with ng2-chart where the error message reads: "RangeError: Maximum call stack size

I encountered an issue with the following error message: ERROR RangeError: Maximum call stack size exceeded at ChartElement.update (Chart.js:11474) at fitBoxes (Chart.js:7127) at fitBoxes (Chart.js:7145) at fitBoxes (Chart.js:7145) at f ...

Is there a way to change a typescript enum value into a string format?

I'm working with enums in TypeScript and I need to convert the enum value to a string for passing it to an API endpoint. Can someone please guide me on how to achieve this? Thanks. enum RecordStatus { CancelledClosed = 102830004, Completed = ...

Downloading PDF files on IOS while using Angular often results in the PDF opening in the same

I'm currently utilizing file-saver within my Angular application to retrieve a PDF generated from the backend. The library functions smoothly on desktop and Android devices, but I'm encountering issues with downloading files on iOS. Contrary to w ...

Http' does not have the 'update' property

I recently implemented Angular 2 Release and utilized 'Http' from '@angular/http' for my project. However, I encountered an error when I invoked the method 'update', which resulted in the following message: "Evidently, th ...

How can Spring Boot be used to format time and save it in the database using the HH:mm format instead of the default HH:mm:ss format?

I'm currently working on a project that involves a spring boot/angular application, and I am facing an issue with sending a time attribute to my REST API in a specific format. I need to send the time in "HH:mm" format instead of the default "HH:mm:ss" ...

Can you explain the distinction between Reflect.getMetadata and Reflect.getOwnMetadata?

Just like the title says, the reflect-metadata API comes with a method called getMetadata and another called getOwnMetadata. Can you explain the distinction between them? The same question applies to hasOwnMetadata, and so on. ...

Implementing shared element route transitions using framer-motion and NextJS (written in typescript)

I'm having trouble implementing animated routing using the <AnimateSharedLayout /> component from framer-motion. What I'm trying to achieve in the code below is to show a list of images and, upon clicking on them, navigate to /images/[image ...

Is it possible for a TypeScript interface to inherit from a Function?

While studying Angular, I found this intriguing declaration: interface IMessagesOperation extends Function { (messages: Message[]): Message[]; } I'm curious about what this means, especially why Function is capitalized as F instead of being lowercase ...

Can I specify which modal or component will appear when I click on a component?

Working on a small Angular 5 project, I have a simple component that represents a food product shown below: [![enter image description here][1]][1] This component is nested within my main component. When this component is clicked, a quantity component/m ...

Cannot utilize a string as an index in an object due to the expression being of type 'string' - this results in an error

What is causing TypeScript to report this error? "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ '&': string; '"': string; "'&qu ...

Preserve data even after refreshing the browser in Angular

Is there a reliable method to preserve my data after refreshing my browser? I've experimented with rxjs behavior subject, but it hasn't worked for me. I prefer not to use local/session storage due to security concerns and best practices, especia ...

Unable to retrieve a property from a variable with various data types

In my implementation, I have created a versatile type that can be either of another type or an interface, allowing me to utilize it in functions. type Value = string | number interface IUser { name: string, id: string } export type IGlobalUser = Value | IU ...

Why is the mat-error not appearing within the mat-form field when using custom global validators in Angular Material 6?

While working with Angular Material 6, I encountered an issue where the mat-error validation inside mat-form-field was not displaying properly. However, when I moved the mat-error code after the mat-form-field, it worked as intended. Here is the non-worki ...

What is the process for designing a mapping type that involves two enums?

I need a solution to connect these two types and create mappings: type MappedEnum<T extends string, A extends string, B extends string> = { [key in T]: {[key in A]: B}; [key in T]: {[key in B]: A}; }; enum Greek { ALPHA = 'A', BET ...

Angular - Error: Cannot read property 'publishLast' of undefined

My goal is to prevent multiple requests from being created when using the async pipe. I am facing an issue with a request to fetch a user from the API: getUser() { this._user = this.http.get<User>(environment.baseAPIUrl + 'user') ...

Encountering issues accessing the key value 'templateUrl' in Angular6

I have an object in my component.ts file that I need to iterate through in the HTML template using a ui-comp-menu element. menuObject = [{ 'labels': 'Content1', 'templateUrl': 'assets/partials/sample.html ...