等待获取请求 - Angular 2

时间:2016-08-29 21:02:14

标签: angular

我收到 GET请求,我想等待响应以运行代码我该怎么做?

我的代码

valid()
{
    let headers = new Headers({ 'Content-Type': 'application/json'});
    let options = new RequestOptions({ headers: headers, method: "get" }); 
    return this.http.get(this.urlstring+ "getisvalid" , options ).toPromise().then(response => response.json());
}

//Code that is in the function

     this._service.valid().then(resut => this.resut = resut);

2 个答案:

答案 0 :(得分:1)

订阅observable时,可以提供回调函数;在下面的示例中,我称之为CompleteValidCallCompleteValidCall()只会在成功获取时调用,返回数据而不是错误。您可以在回调函数中放置所需的逻辑。

this._service.valid()
   .subscribe(
      result => this.result = result,
      error => this.error = error,
      () => this.CompleteValidCall()
);

completeValidCall() {
  // the rest of your logic here - only executes on obtaining result.
}

答案 1 :(得分:0)

this.http.get返回Observable,所以你必须订阅它。如果您将valid()更改为:

valid() {
  let headers = new Headers({ 'Content-Type': 'application/json'});
  let options = new RequestOptions({ headers: headers, method: "get"}); 
  return this.http.get(this.urlstring+ "getisvalid" , options ).map(response => response.json());
}

然后使用:

this._service.valid().subscribe(resut => this.resut = resut);