Angular 2 Observables consistently deliver undefined results

I keep encountering an issue where I am always receiving 'undefined' in my component code. Any assistance on this matter would be greatly appreciated.

When I attempt to write to the console, it consistently returns 'undefined'.

I am currently working with Angular2 and utilizing Visual Studio Code as my editor. Below you will find both my service and component code:

**Service Code**
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';

export interface GitHubUser {
  html_url: string;
  avatar_url: string;
  login: string;
  score: string;
}

@Injectable({
  providedIn: 'root'
})
export class GitHubServiceService {

  constructor(private _http: HttpClient) { 
  }

  getGitHubData(_searchTerm): Observable<GitHubUser[]> {
    return this._http.get<GitHubUser[]>("https://api.github.com/search/users?q="+_searchTerm);
  }
}

Component Code

import { Component } from '@angular/core';
import { GitHubServiceService, GitHubUser } from './git-hub-service.service';
import { filter, switchMap, debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { FormControl } from '@angular/forms';
import { Observable, of } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  users: GitHubUser[];
  data$: Observable<GitHubUser[]>;
  title = 'app';

  constructor(private _githubService: GitHubServiceService){
       this.data$ = this._githubService.getGitHubData('greg');
       this.data$.subscribe(users => this.users = users);
       console.log(this.users);
       console.log(this.users.length);
    }
}

Answer №1

It appears that you may be printing the value prematurely. The search request likely has not completed by the time you attempt to print the value to the console.

Consider printing inside the subscribe function instead:

this.data$.subscribe(users=> {
   this.users = users;
   console.log(this.users);
   console.log(this.users.length);
});

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

What is the best way to set a checkbox to null instead of false using Angular?

I am currently developing a filtering system that allows users to select different parameters to filter through a list of items. For instance, the item list could be a collection of dishes with filters represented as checkboxes labeled as vegan, vegetaria ...

What is the best way to communicate an event occurring within the ng-content to the reusable parent component in Angular?

I am looking to create a versatile dropdown component in Angular that can display different content such as a list or a tree. Essentially, I want to be able to extract the selection label that triggers the dropdown to open and close upon clicking. dropdow ...

What is the best method for comparing arrays of objects in TypeScript for optimal efficiency?

Two different APIs are sending me arrays of order objects. I need to check if both arrays have the same number of orders and if the values of these orders match as well. An order object looks like this: class Order { id: number; coupon: Coupon; customer ...

Checking React props in WebStorm using type definitions

Currently, I am utilizing WebStorm 2018.3.4 and attempting to discover how to conduct type checking on the props of a React component. Specifically, when a prop is designated as a string but is given a number, I would like WebStorm to display an error. To ...

How can I display the top 5 data results after subscribing in Nativescript?

Utilizing this function allows me to retrieve all my data from the web service. public data: Data[]; getall() { this.ws.getalldata().subscribe( data=> { this.data= data; } ); } Here is a ...

Implementing Asynchronous Custom Validators in Angular 4

I've encountered the following code snippet: HTML: <div [class]="new_workflow_row_class" id="new_workflow_row"> <div class="col-sm-6"> <label class="checkmark-container" i18n>New Workflow <input type="che ...

angular directive to receive an object

When I have a table and click on a row, the information is supposed to be displayed in a different component using the @input decorator. However, instead of displaying the correct result in my other component, I am getting [object Object]. table.html < ...

The 'Server' type is not designed to be generic

Out of nowhere, I encountered the following error: TypeScript: ./..\..\node_modules\@types\ws\index.d.ts:328:18 Type 'Server' is not generic. Angular CLI: 13.3.11 Node: 16.13.2 Package Manager: npm 8.1.2 OS: win3 ...

What could be causing the issue with "class not being recognized as a constructor" error that I am encountering?

When attempting to create an instance from modules in routing, I consistently encountered the error message "class is not a constructor." Below is the code snippet: export class Modules{ modules : object = { masterdata : MasterdataModule, shop : ...

Utilizing Angular to lazily load multiple routes/paths within a single module

I am currently in the process of setting up multiple horizontal routes (not nested) and grouping them into one lazy-loaded module. However, I am facing a challenge trying to properly match these routes within the lazy-loaded feature module itself. Below ...

Tips for troubleshooting Angular 4 unit testing using jasmine and karma with simulated HTTP post requests

I have a service that I need to unit test in Angular 4 using TypeScript and Jasmine. The problem is with the http where it needs to perform a post request and get an identity in return, but for some reason, no data is being sent through. My goal is to ac ...

Steps to establish a maximum font size for my buttons

I've been working on creating buttons to decrease and increase the font size of my text. The functionality is there, but I want to establish a limit on how small or large the font can go. Here's what my current code looks like: <md-button ng ...

What is the process for being directed to the identity server login within an Angular application?

Immediately redirecting users to the identity server upon accessing the application is my goal. Currently, there is a login button that directs users to the ID server with a click, but I want to eliminate this button and have the redirection occur automati ...

Only Story members are permitted to read in Firestore security rules

Lately, I've been diving into the world of firestore and encountering a persistent struggle. Within my firestore database, there exist Story documents structured as follows: story: { name: 'James', members: { 'WeWF34RFD23RF23& ...

Updating a subscribed observable does not occur when pushing or nexting a value from an observable subject

Help needed! I've created a simple example that should be working, but unfortunately it's not :( My onClick() function doesn't seem to trigger the console.log as expected. Can someone help me figure out what I'm doing wrong? @Component ...

Having trouble with the Angular 17 Router functionality when running on a node server

I find myself facing an unusual situation. I am currently developing a basic app that needs to navigate from the landing-page (directory '') to a form component (directory '/form') using Angular 17 and node.js with express.js. I have no ...

Understanding TypeScript typing when passing arguments to the Object.defineProperty function

After reviewing all the suggested answers, including: in Typescript, can Object.prototype function return Sub type instance? I still couldn't find a solution, so I'm reaching out with a new question. My goal is to replicate Infix notation in J ...

The ngx-image-cropper's roundCropper attribute is not functioning correctly as it should. An error is being displayed stating: "Type 'string' is not assignable to type 'boolean'"

<image-cropper [imageChangedEvent]="imageChangedEvent" [maintainAspectRatio]="true" [aspectRatio]="4 / 4" format="jpg" (imageCropped)="imageCropped($event)" roundCropper = "true"> </i ...

Guide on implementing autocomplete in Angular Material with a dynamic SQL data source

I struggled to get it working using the mat-table option and even searched on YouTube, only finding hard-coded autocomplete examples. I have included some relevant code segments - thank you for your assistance. Visit this link for more information on Angu ...

Obtaining an array of objects through the reduction of another array

Currently, my goal is to extract an array of objects from another array. Let's say I have an array consisting of strings: const strArr = ["Some", "Thing"]; The task at hand is to create a new Array containing 2 objects for each st ...