Gaurav
Gaurav

Reputation: 623

Angular 2 Observable always returns undefined

I am always getting undefined in my component code. Any help will be greatly appreciated.

If I try to write in console it returns 'undefined' .

I am using Angular2 and using Visual studio code as editor. Below is 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);
    }


  }

Upvotes: 0

Views: 240

Answers (1)

PeS
PeS

Reputation: 4039

You are printing the value too soon. The request to search was most probably not finished by the time you print the value to console.

Try to print that in subscribe:

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

Upvotes: 2

Related Questions