簡體   English   中英

angular 2 http.get subscription:服務完成后如何調用另一個函數?

[英]angular 2 http.get subscribe: How to call another function when service completed?

不明白 如果我需要我的結果做更多​​的事情,不僅要輸入例如可變英雄。 我想在成功或完成時調用另一個函數,但我做不到。 為什么會這樣,應該怎么做? 我還有另一個變量需要獲取從響應返回的相同數據(它的副本),但只有在獲取數據后才能進行復制。

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

您可以在收到響應后立即調用該函數。

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

擴展此類用戶提供的內容:

您無法訪問其他組件變量的原因是因為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'); }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM