2017-02-24 57 views
-1

不明白。如果我需要我的結果來做更多的事情,那麼不要只輸入我的變量heros。我想調用成功或完成的另一個功能,但我不能。爲什麼是這樣,應該怎麼做?我有另一個變量需要獲取從響應返回的相同數據(它的副本),但是我只能在獲取數據後才能創建副本。angular 2 http.get訂閱:如何在服務完成時調用另一個函數?

this.myService.getHeroes() 
    .subscribe(
     function(response) { 
      response => this.heros = response; 
     }, 
     function(error) { 
      console.log("Error happened" + error) 
     }, 
     function() { 
      console.log("the subscription is completed"); 
     } 
    ); 
+0

首先你的語法是錯誤的,不會transpile。你需要'(response)=> this.heros = response;'和** not **'function'和箭頭函數的組合。 – Igor

+0

10x我檢查它,但仍然是同一個問題。就像我不能從成功/錯誤/完整功能內調用任何其他函數 – AngularOne

+0

首先你必須定義一個函數,然後調用它/: –

回答

4

您可以在獲得響應後立即調用該函數。

this.myService.getHeroes() 
 
    .subscribe(res => { 
 
     this.heros = res; 
 
     //insert whatever you want here, e.g. function which needs to wait for asynchro response 
 
    }, 
 
    error => { 
 
     console.log("Error happened" + error) 
 
    } 
 
);

+0

不,我得到錯誤,你的函數不是函數 – AngularOne

+0

@AngularOne我剛纔調用它作爲一個例子...你可以插入任何你想要的,例如你的一些函數必須等待異步響應。您也可以刪除它。 –

+1

@AngularOne @Kinduser是對的。你應該在''this.heroes = res''之後調用你的''function''。 「Observer」在Observable結束操作時調用Observable''complete''函數。但如果它不呢?也許這個流是無限的,那麼''complete''永遠不會叫 – lomboboo

1

要在這樣一種用戶提供了哪些擴展:

的原因,你無法訪問您的其他組件變量是因爲this關鍵字的範圍被封裝到函數內只有不再瞭解組件變量。

爲了引用組件變量,你必須利用lambda表達式來代替:

@Component({ 
    selector: 'app-browse', 
    templateUrl: './browse.component.html', 
    styleUrls: ['./browse.component.css'] 
}) 
export class BrowseComponent implements OnInit { 

    constructor(private myService: MyService) { } 

    myString: string = 'dogs'; 

    doStuff() { 
    this.myService.doMoreStuff().subscribe(returnValue => { 
     console.log(this.myString); // 'dogs' 
     this.myOtherFunction(); // 'other stuff' 
    }); 

    this.myService.doMoreStuff().subscribe(function(returnValue) { 
     console.log(this.myString); // undefined 
     // myString does not exist with the scope of this function 
     var myString = 'cats'; 
     console.log(this.myString); // 'cats' 
    }); 
    } 

    myOtherFunction() { console.log('otherStuff'); } 

} 
相關問題