Angular 2 Observable always returns undefined












0














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


}









share|improve this question



























    0














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


    }









    share|improve this question

























      0












      0








      0







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


      }









      share|improve this question













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


      }






      angular typescript rxjs observable






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 11 '18 at 23:52









      Gaurav

      58229




      58229
























          1 Answer
          1






          active

          oldest

          votes


















          2














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





          share|improve this answer





















          • Thanks, But it's not the case. If I use this - subscribe(data=>console.log(data)). I am able to print all in console.
            – Gaurav
            Nov 12 '18 at 0:03












          • Well, I beg to differ - that is exactly the case. See the difference (and similarity) between your code in question, mine in reply and your in the comment.
            – PeS
            Nov 12 '18 at 0:07










          • Adding to what @PeS mentioned, this is the function decription of subcribe(next, error, complete). It has three callbacks next(), error(), complete(). In an asynchronous execution scenario your console.log outside subcribe() will run before a response could be arrived from the http call. Thats y you should put console.log in the next() part of the callback. here next is "users => {}" part.
            – KiraAG
            Nov 12 '18 at 5:53













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254425%2fangular-2-observable-always-returns-undefined%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














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





          share|improve this answer





















          • Thanks, But it's not the case. If I use this - subscribe(data=>console.log(data)). I am able to print all in console.
            – Gaurav
            Nov 12 '18 at 0:03












          • Well, I beg to differ - that is exactly the case. See the difference (and similarity) between your code in question, mine in reply and your in the comment.
            – PeS
            Nov 12 '18 at 0:07










          • Adding to what @PeS mentioned, this is the function decription of subcribe(next, error, complete). It has three callbacks next(), error(), complete(). In an asynchronous execution scenario your console.log outside subcribe() will run before a response could be arrived from the http call. Thats y you should put console.log in the next() part of the callback. here next is "users => {}" part.
            – KiraAG
            Nov 12 '18 at 5:53


















          2














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





          share|improve this answer





















          • Thanks, But it's not the case. If I use this - subscribe(data=>console.log(data)). I am able to print all in console.
            – Gaurav
            Nov 12 '18 at 0:03












          • Well, I beg to differ - that is exactly the case. See the difference (and similarity) between your code in question, mine in reply and your in the comment.
            – PeS
            Nov 12 '18 at 0:07










          • Adding to what @PeS mentioned, this is the function decription of subcribe(next, error, complete). It has three callbacks next(), error(), complete(). In an asynchronous execution scenario your console.log outside subcribe() will run before a response could be arrived from the http call. Thats y you should put console.log in the next() part of the callback. here next is "users => {}" part.
            – KiraAG
            Nov 12 '18 at 5:53
















          2












          2








          2






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





          share|improve this answer












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






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 11 '18 at 23:56









          PeS

          1,32521222




          1,32521222












          • Thanks, But it's not the case. If I use this - subscribe(data=>console.log(data)). I am able to print all in console.
            – Gaurav
            Nov 12 '18 at 0:03












          • Well, I beg to differ - that is exactly the case. See the difference (and similarity) between your code in question, mine in reply and your in the comment.
            – PeS
            Nov 12 '18 at 0:07










          • Adding to what @PeS mentioned, this is the function decription of subcribe(next, error, complete). It has three callbacks next(), error(), complete(). In an asynchronous execution scenario your console.log outside subcribe() will run before a response could be arrived from the http call. Thats y you should put console.log in the next() part of the callback. here next is "users => {}" part.
            – KiraAG
            Nov 12 '18 at 5:53




















          • Thanks, But it's not the case. If I use this - subscribe(data=>console.log(data)). I am able to print all in console.
            – Gaurav
            Nov 12 '18 at 0:03












          • Well, I beg to differ - that is exactly the case. See the difference (and similarity) between your code in question, mine in reply and your in the comment.
            – PeS
            Nov 12 '18 at 0:07










          • Adding to what @PeS mentioned, this is the function decription of subcribe(next, error, complete). It has three callbacks next(), error(), complete(). In an asynchronous execution scenario your console.log outside subcribe() will run before a response could be arrived from the http call. Thats y you should put console.log in the next() part of the callback. here next is "users => {}" part.
            – KiraAG
            Nov 12 '18 at 5:53


















          Thanks, But it's not the case. If I use this - subscribe(data=>console.log(data)). I am able to print all in console.
          – Gaurav
          Nov 12 '18 at 0:03






          Thanks, But it's not the case. If I use this - subscribe(data=>console.log(data)). I am able to print all in console.
          – Gaurav
          Nov 12 '18 at 0:03














          Well, I beg to differ - that is exactly the case. See the difference (and similarity) between your code in question, mine in reply and your in the comment.
          – PeS
          Nov 12 '18 at 0:07




          Well, I beg to differ - that is exactly the case. See the difference (and similarity) between your code in question, mine in reply and your in the comment.
          – PeS
          Nov 12 '18 at 0:07












          Adding to what @PeS mentioned, this is the function decription of subcribe(next, error, complete). It has three callbacks next(), error(), complete(). In an asynchronous execution scenario your console.log outside subcribe() will run before a response could be arrived from the http call. Thats y you should put console.log in the next() part of the callback. here next is "users => {}" part.
          – KiraAG
          Nov 12 '18 at 5:53






          Adding to what @PeS mentioned, this is the function decription of subcribe(next, error, complete). It has three callbacks next(), error(), complete(). In an asynchronous execution scenario your console.log outside subcribe() will run before a response could be arrived from the http call. Thats y you should put console.log in the next() part of the callback. here next is "users => {}" part.
          – KiraAG
          Nov 12 '18 at 5:53




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254425%2fangular-2-observable-always-returns-undefined%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Coverage of Google Street View

          Full-time equivalent

          Surfing