[英]Angular Http Subscribe not working
嗨,在我的 Angular 组件中,我的方法之一中有此代码
this.http.get("http://localhost:8080/poeples")
.map(
resp => { resp = resp.json(); }
).subscribe(
(data) => { this.poeples = data; },
err => console.log(err)
);
在 Chrome 开发检查器的网络选项卡中,我看到我的 get 调用返回结果,但data
未定义。
为什么?
它最初不起作用的原因是因为你有这个:
resp => { resp = resp.json(); }
您没有返回值。 使用花括号时,必须明确定义返回值。 你所要做的就是:
resp => { return resp.json(); }
或删除括号:
resp => resp.json()
// Your code that isn't working: /*this.http.get("http://localhost:8080/poeples") .map( resp => { resp = resp.json() } ).subscribe( (data) => { this.poeples = data; }, err => console.log(err)) ;*/ // Working code: @import { map } from 'rxjs/operators'; this.http.get('http://localhost:8080/poeples') .pipe( // In your example, you are creating a new function with the {} wrapped around this line, but you aren't returning anything, so the return value of the "data" below becomes "undefined." map((response) => response.json()) ) .subscribe( (data) => { this.poeples = data; }, (err) => console.log(err) );
错误 - 订阅请求成功代码无效时。 这是我正在处理的代码
this.userService.addDeliverDetails(form.value) .subscribe( res=>{ this.have=true; }, error=>{ console.log('error') } );
尝试在 console.log() 出错,如果它记录了这意味着您的数据来自服务器,而不是 JSON 格式的文本。
两种解决方案 1) 更改 angular 以接受文本响应 2) 将服务器响应更改为 json 而不是字符串(纯文本)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.