Lambda Expression failing to function correctly

I'm struggling to set a value to an array within an Observable using a Lambda expression.

Here is a snippet of my class:

usuarios: Usuario[];

Currently, I am utilizing an Http service for injection.

Within one of my functions, I have the following code:

getUsuarios(): Usuario[] {

    this._http.get("http://localhost:3000/db").map(data => data.json()).subscribe(data => {
      this.usuarios = data["Usuarios"];
      console.log(this.usuarios);
    });

    console.log(this.usuarios);

    return this.usuarios;
  }

Strangely enough, the first console log output (within the lambda expression) shows the data correctly in the console. However, upon another attempt to log it outside the lambda expression, this.usuarios appears empty and undefined.

Any insights into why this behavior is occurring?

Answer №1

Everything seems to be in proper working order, as the expected console output should look like this:

undefined
...some data

The reason behind this is that when using http requests, they are asynchronous, meaning that the first console.log() will not get executed until a response from the http request is received.
The 2nd console.log(), being outside the scope of the http request, will execute before it. You can find more detailed information about this topic 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

How to extract the chosen option from a bound list within an Angular application

Our goal is to avoid using 2-way binding in our component setup: <select type="text" formControlName="region" (change)="regionChanged($event)"> <option *ngFor="let region of regionsDDL" [ngValue]="region">{{region.name}}</option> ...

Create a new object containing a series of function expressions, but exclude the first function parameter

In my current setup, I have a variable called storePattern const storePattern = { state: { }, mutations: { }, actions: {}, modules: { modal: { actions: { openModal(store, name: string): boolean { console.log('Op ...

Error: DecimalProvider is not provided by the injector

Encountering the following error message: NullInjectorError: R3InjectorError(StudentModule)[DecimalProvider -> DecimalProvider -> DecimalProvider -> DecimalProvider]: https://i.stack.imgur.com/e8D6o.png Despite importing the DecimalPipe into the ...

Developing personalized angular decorators

I've been working on creating custom decorators that can return a new instance of a class. The catch is that this class needs to be created from an injected service, and I'm struggling to access it from the decorator function. Custom Decorator ...

The Postman tool is able to provide a successful response, but when attempting to call the same API through Angular code,

After successful postman calls to the API, I encountered an error when trying to call the same API in my Angular application. The error message received from the backend is shown below: https://i.stack.imgur.com/CrMwM.png The error messages are as follow ...

Tips for resolving the TSLint error in Firestore related to the possibly undefined object

I've been working with Firestore using the code snippet provided in this link. However, I keep encountering an error that says Object is possibly 'undefined' when trying to access data.name. I'm confident that the document does contain ...

Encountering problem with Http error in Angular2 rc1 Subscription

Attempting to incorporate my http service component using the following link: Here is my service component: import {Injectable} from '@angular/core'; import {Http, Response} from '@angular/http'; import {Observable} from 'rxjs/Rx ...

What are some ways to streamline this repetitive angular code using promises?

As a newcomer to Angular development, I'm curious if there's a more elegant way to streamline the repetitive code shown below. addTransaccion() { try { if (this.idTransaccion === '0') { this.transaccionesSrv.addTransa ...

Implementing form validation in Angular2 without using the <form> tag

Is there a way to perform form validation in Angular 2 without using the typical form tag setup? For instance, I would like to set a required field below: <div class="form-group"> <label for="name">Name</label> <input type=" ...

I consistently encountered errors while working with the Angular Firestore database

I kept encountering the following error message: src_app_ddd_module_ts.js:2 ERROR Error: Uncaught (in promise): Error: Either AngularFireModule has not been provided in your AppModule (this can be done manually or implictly using provideFirebaseApp) or yo ...

Tips on setting up an npm package for automatic updates

I recently created a package called https://www.npmjs.com/package/nestjs-notifications After running npm install nestjs-notifications --save, I noticed that it installed successfully but saved the version as: "nestjs-notifications": "0.0.10 ...

Tips on navigating to the next or previous variable reference in VS Code

While using TypeScript in VS Code, is there a similar shortcut like in Visual Studio for easily navigating between variable references within the open script? ...

How can I link types from @types to my local code?

I've created a method that utilizes validatorjs for validation purposes. Here's an example of the code: /** * Checks if the string is a mobile phone number (locale options: ['zh-CN', 'zh-TW', 'en-ZA', 'en- ...

TypeScript types for d3 version 4

I am currently working on a d3 project and to simplify the development process and reduce errors, I decided to implement TypeScript. Using d3 v4, I initially faced issues with incorrect type definitions which led to errors like d3 not having a definition ...

What could be causing the failure to typecheck the sx prop?

Trying to implement sx prop-based styling in a React project. Looking to utilize the theme using a theme getter. While styles render correctly in the browser, TypeScript raises errors and understanding the type ancestry is proving challenging. Working e ...

Utilize Firebase Realtime Database to generate new data entries using triggers

Hey there, to all the amazing folks at stackoverflow who have been supporting me over the years, I have a new question for you! I've been delving into Android programming for quite some time now and I enjoy exploring different ways to optimize apps. ...

Why am I struggling to show the success message on my basic CRM Angular web application?

I'm facing an issue in my Basic Angular app where the success message is not being displayed even after writing the correct code. 1)app.component.html <h1 class="c1">{{title}}</h1> <div *ngIf="success_msg;" style=&q ...

Tips for incorporating JSON in server-side rendering using Angular Universal

Currently, I am in the process of developing an angular2-universal app for a university project which is also my bachelor thesis. My goal is to have this app rendered on the server using angular universal. However, I am facing a challenge in loading my .js ...

Navigating the dot notation to uncover the data type of a field within an object

When working with an object type, we can access the type of one of its fields using bracket-string notation. However, why isn't it possible to use dot notation like in JavaScript? Could there be a conflict or some other reason for this limitation? I h ...

Poorly packaged library - Custom Angular library - Node Package Manager

Recently, I've been delving into the process of publishing a simple Angular library on NPM. Despite following various tutorials (like those found here, here, and here), I faced difficulties when attempting to use it in a test project. MY JOURNEY In s ...