创建一个同步的http.get() [英] create a synchronous http.get()

查看:263
本文介绍了创建一个同步的http.get()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Promise和http.get处理登录,但是我失败得很厉害,收到以下错误消息:

Im trying to handle a login via promises and http.get but i fail so hard I get following error :

对象不支持属性或方法"toPromise"

Object doesn't support property or method 'toPromise'

我的代码是:

return this.http.get('http://localhost:5000/login/', {
  headers: authHeader
}).map((response) => {
  return response.json()
}).toPromise(null);

ive是从:

https://github.com/johnpapa/angular2-there-and-back-again/blob/master/src/app/core/character.service.ts

更新:

JohnPapa我的朋友们更新了他的项目

JohnPapa updated his project my friends

https://github.com/johnpapa/angular2-there-and-back-again/blob/master/app/core/character.service.ts

推荐答案

我想知道您是否真正使用了promise,因为Angular的HTTP支持依赖于Observables.

I wonder if you actually use promise since the HTTP support of Angular relies on Observables.

要获得响应,您只需要返回可观察的呼叫即可:

To get the response, you simply need to return the observable for your call:

getSomething() {
  return this.http.get('http://localhost:5000/login/', {
    headers: authHeader
  }).map((response) => {
    return response.json()
  })
}

调用该方法时,可以使用subscribe方法注册回调:

When calling the method, you can then register callbacks using the subscribe method:

getSomething().subscribe(
  data => handleData(data),
  err => reject(err));

如果您真的要使用诺言(通过toPromise方法),则应导入以下内容:

If you really want to use promises (with the toPromise method), you should import this:

import 'rxjs/Rx';

有关更多详细信息,请参见此问题: https://github.com/angular/angular/issues/5632#issuecomment-167026172 .

See this issue for more details: https://github.com/angular/angular/issues/5632#issuecomment-167026172.

否则,FYI调用与浏览器中的HTTP不同步...

Otherwise, FYI calls aren't synchronous regarding HTTP in browsers...

希望它对您有帮助, 蒂埃里

Hope it helps you, Thierry

这篇关于创建一个同步的http.get()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆