简体   繁体   中英

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);
    }


  }

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM