2017-02-24 75 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'); } 

} 
相关问题