angular 2 http.get 订阅:服务完成后如何调用另一个函数?

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, e.g. 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'); }

}