Angular 8 Observable: Managing User Objects

I recently developed a new service and attempted to call an API method (HTTP GET) to retrieve data, but I'm encountering an issue where not all the data objects from the API GET request are being displayed.

angular-component.ts

public allUsers$: Observable<User[]>;
constructor(private usersService: UsersService) { }
ngOnInit() {
   this.allUsers$ = this.getAllUsers();
   console.log(this.allUsers$) 
}
private getAllUsers(): Observable<User[]> {
   return this.usersService.getUsers(); 
}

Upon checking the console, the following message is displayed:

https://i.sstatic.net/r1MqO.png

users.service.ts

public getUsers(): Observable<User[]> {
  return this.apiService.get(this.type) as Observable<User[]>;
}

api.service.ts

public get(url: string): Observable<any> {
   return this.http.get(environment.apiUrl + `/${url}`);
}

nodejs-route.js

app.get("/", async (req, res) => {
  const getAllUsers = await User.find().populate("orders.order_id");
  res.status(200).send(getAllUsers);
});

Answer №1

Remember, an Observable is essentially inert.

Ben Lesh, a prominent figure in RxJS development, once explained:

Observables themselves are inert. They don't actively stream or perform actions. Instead, they serve as blueprints for streaming, actions, or observations that will occur upon subscription.

There are two primary ways to subscribe to an Observable:

  1. Utilizing an async pipe.
  2. Directly using the subscribe method.

When using an async pipe in a template, automatic subscription and unsubscription are handled for you.

For instance, your template might include:

<div class="card"
     *ngIf="allUsers$ | async as users">

This allows you to access the users data in your template, perhaps through an *ngFor directive.

However, obtaining data for use in your component code can be trickier with an async pipe. A simple console.log(this.allUsers$) will merely display Observable information.

An alternative method involves manual subscription within your component:

sub: Subscription
users: User[]

ngOnInit() {
   this.sub = this.getAllUsers().subscribe(
    users => {
       this.users = users;
       console.log(users);
    );
}

The subscribe() method yields a Subscription object, allowing for manual unsubscription if necessary.

Ultimately, this approach results in an array of users User[] rather than an Observable<User[]>, making data binding in your template straightforward.

Typically, utilizing the async pipe is the recommended strategy.

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

Angular EventEmitter coupled with Callbacks

In order to create a custom button component for my angular application and implement a method for click functionality, I have the following code snippet: export class MyButtonComponent { @Input() active: boolean = false; @Output() btnClick: EventEmit ...

Console not logging route changes in NextJS with TypeScript

My attempt to incorporate a Loading bar into my NextJs project is encountering two issues. When I attempt to record a router event upon navigating to a new route, no logs appear. Despite my efforts to include a loading bar when transitioning to a new rout ...

Ensuring the accuracy of the angular-formly form definition

I am currently involved in a project where users can input a JSON formly form definition that gets saved into the database. This definition will later be utilized to create a form. Before storing this JSON definition in the database, I need to validate it ...

Best location for Angular PWA update handler?

Running a PWA app led me to think about decluttering the application.component. To achieve this, I created a dedicated service to monitor PWA updates and alert the user: import { Injectable } from '@angular/core'; import { MatSnackBar } from &qu ...

Showing an error message upon submission in Angular 4 according to the server's response

Struggling for hours to display an error message when a form submits and returns an error status code. The solution seems elusive... In the login form component below, I've indicated where I would like to indicate whether the form is valid or invalid ...

issue with global variable not functioning properly within a sub-function in Angular 7

I have a question that needs clarification import { Component, OnInit,ViewChild,ElementRef } from '@angular/core'; import {Http,Headers} from "@angular/http"; import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, ...

What is the best way to retrieve all values for a specific JsonProperty name from a JsonDocument?

Within a free-form JsonDocument, there exists a JsonProperty named internalName. The challenge lies in parsing this data without a predefined JSON schema, as the property can be located at various levels within the JSON structure. How can one retrieve all ...

What's the best way to append a comma to the end of each line in a massive 3 GB text file

I am facing an issue with a 3GB dataset named with a .json extension. My goal is to add a comma at the end of each line except the last one in order to validate the JSON file and import it into Excel. Unfortunately, Notepad++ does not support such large fi ...

Maximizing the potential of Angular forms through native FormData

Currently, I am revisiting an older project that still uses traditional methods for form submission. The HTML includes a form element with defined method and action. My goal is to submit the form in the old-fashioned way using the action attribute to post ...

Troubleshooting MySQL through PHP for errors

I've developed a comment posting system where users can write and submit comments using PHP, MySQL, jQuery, AJAX, and JSON. However, I encountered an issue with JSON insertion while debugging the system with Firebug. The error message displayed was: ...

Establishing a connection to an API with basic authentication in Angular 8 and Express JS

After setting up my angular 8 app and connecting it to an express API, I decided to run it locally for testing purposes. The front end of the app connects to http://localhost:4200/, while the backend connects to http://localhost:3000/. Additionally, I crea ...

Exploring Angular: How to access ViewChild from a dynamically loaded component

One of my components includes a ViewChild element like this: @ViewChild('overView') content: ElementRef; I am dynamically loading this component in the following way: let overviewComponent = this.vcr.createComponent(OverviewComponent); let conte ...

Working with intricately structured objects using TypeScript

Trying to utilize VS Code for assistance when typing an object with predefined types. An example of a dish object could be: { "id": "dish01", "title": "SALMON CRUNCH", "price": 120, ...

Display a loading indicator in Angular during app initialization with APP_INITIALIZER

Is there a way to display a waiting indicator while the Angular app is running the app_initializer code? Currently, I can display a waiting indicator until the app is fully loaded. However, once the page loads, it remains empty until the app_initializer c ...

Retrieve solely the text content from a JavaScript object

Is there a way to extract only the values associated with each key in the following object? const params = [{"title":"How to code","author":"samuel","category":"categoery","body":"this is the body"}] I'm struggling to figure out how to achieve this. ...

Setting up jsonReader for jqGrid Configuration

I am having trouble displaying data in my Jqgrid. The Json data is coming from a web server, so I am attempting to format it using Jsonreader as a function. Could someone please help me identify any mistakes? Thank you in advance. Here is the code for the ...

Guide to sending JSON data in Lua with cURL

Can someone help me with posting json in Lua using cURL? I've been searching online for examples but can't seem to find any. Here's the code snippet that I'm working with: c = curl.easy{ url = "http://posttestserver.com/pos ...

Cleaning arrays in Angular 2 forms: A step-by-step guide

Need some assistance. I'm developing an app in Angular2(4) which includes a Form with 2 select boxes and 1 checkbox. My goal is to establish a dependency between these boxes using the following array: dataJSON = [ { productName: 'Produ ...

The function failed to obtain JSON data from the generated URL

I want to fetch the latest local weather details using a weather API. Below is the code I am working with: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> function generateUrl() { var ap ...

I followed the step to download Angular using NPM Install

When attempting to work on a repository that uses Angular without having it installed on my machine, I ran npm i. However, Angular was not automatically installed. So, I had to separately install the Angular CLI before running ng serve --open ...