简体   繁体   English

Angular Http 订阅不起作用

[英]Angular Http Subscribe not working

Hi In my Angular Component, i have this code in one of my methods嗨,在我的 Angular 组件中,我的方法之一中有此代码

this.http.get("http://localhost:8080/poeples")
.map(
    resp => { resp = resp.json(); }
).subscribe(
    (data) => { this.poeples = data; },
    err =>  console.log(err)
);

In network tab in chrome dev inspector i saw that my get call returning result, but data is undefined.在 Chrome 开发检查器的网络选项卡中,我看到我的 get 调用返回结果,但data未定义。

Why?为什么?

The reason it was not working originally, is because you had this:它最初不起作用的原因是因为你有这个:

resp => { resp = resp.json(); }

You are not returning a value.您没有返回值。 When you use the curly braces, you have to explicitly define a return value.使用花括号时,必须明确定义返回值。 All you had to do was:你所要做的就是:

resp => { return resp.json(); }

Or remove the braces:或删除括号:

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) );

Error - when subscribing request success code not working.错误 - 订阅请求成功代码无效时。 This is my code I'm working on这是我正在处理的代码

this.userService.addDeliverDetails(form.value) .subscribe( res=>{ this.have=true; }, error=>{ console.log('error') } ); this.userService.addDeliverDetails(form.value) .subscribe( res=>{ this.have=true; }, error=>{ console.log('error') } );

Try to console.log() in error and if it logged that's mean your data coming from the server as text not JSON formatted.尝试在 console.log() 出错,如果它记录了这意味着您的数据来自服务器,而不是 JSON 格式的文本。

Two solutions 1) change angular to accept text responses 2) change server response to json not to string (plain text)两种解决方案 1) 更改 angular 以接受文本响应 2) 将服务器响应更改为 json 而不是字符串(纯文本)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM