2016-08-31 132 views
0

我有一個簡單的服務,它獲取github用戶的回購並正確返回數組對象角2:訂閱可觀察到的產量「未定義」?

githubservice

getRepos(){ 
     return this._http.get(this._url + this.username +"/repos") 
     .map(users =>{   
      this.u = users.json(); 
      console.log("getRepos", this.u); //<== correctly returns array object 
      }); 
    } 

,當我在組件訂閱它,然後我得到了一個未定義。

githubcomponent

getReposFromGithub(){ 
     return this._githubService.getRepos().subscribe(repos => { 
     this.repos = repos; 
     console.log("repos", repos);}, //<== logs 'undefined' 
     (error)=> console.log("error message",error), //<== no error message 
     ()=>{console.log("completed");} //<== gets logged 
     ); 
    } 


ngOnInit() { 
     console.log("on changes"); 
     this.getReposFromGithub(); 
    } 

僅供參考,這裏是數組對象返回

enter image description here

我失去了什麼嗎?也許要使用一些rxjs操作? 在此先感謝!

回答

3

你不會從.map呼叫getRepos()返回任何東西。你可能意思是返回結果數組。加上return this.u;,像這樣:

getRepos() { 
    return this._http.get(this._url + this.username +"/repos") 
    .map(users => {   
     this.u = users.json(); 
     console.log("getRepos", this.u); //<== correctly returns array object 
     return this.u; 
    }); 
} 
+0

謝謝。我知道這將是我的一個愚蠢的錯誤。我也可以在單行中使用'.map(users => users.json());'。 – candidJ

+0

@candidJ它發生了。 :) 樂意效勞。 –

2

mapgetRepos中使用的lambda函數不返回任何內容。

+0

謝謝。我最初使用單行(所以不需要使用返回),但後來想到記錄結果到控制檯。 – candidJ