Javascript 我无法从JSONP';获取主体数据;s使用Angular2进行响应,但它使用ajax工作

Javascript 我无法从JSONP';获取主体数据;s使用Angular2进行响应,但它使用ajax工作,javascript,jquery,ajax,angular,jsonp,Javascript,Jquery,Ajax,Angular,Jsonp,首先,我使用spring boot对服务器进行了编码,代码如下: public class App { @RequestMapping("/") @ResponseBody String home(HttpServletRequest request) { String aa=request.getParameter("callback"); System.out.println(request.getParameter("callback")); return aa+"

首先,我使用spring boot对服务器进行了编码,代码如下:

public class App {
@RequestMapping("/")
@ResponseBody
String home(HttpServletRequest request) {
    String aa=request.getParameter("callback");
    System.out.println(request.getParameter("callback"));
    return aa+"({\"text\":\"hello,world\"})";
}
public static void main(String[] args) throws Exception {
    SpringApplication.run(App.class, args);
}}
其次,我用Angular2对前端进行编码:

export class HomePage implements OnInit{
  constructor(private jsonp:Jsonp) {
      }
  ngOnInit(): void {
    this.jsonp.get("http://localhost:8080/callback=JSONP_CALLBACK")
      .subscribe(res=>console.log(this.res);    
  );    
}}
然后,我在ng serve中运行前端,并从控制台获取信息:

Response {_body: Object, status: 200, ok: true, statusText: "Ok", headers: Headers…}
function () {
        if (typeof this._body === 'string') {
            return JSON.parse(/** @type {?} */ (this._body));
        }
        if (this._body instanceof ArrayBuffer) {
            return …
显然,“_body:Object”包含我想要的数据,实际上,数据如下所示:

{"text":"hello,world"}
因此,我尝试获取数据,但Observable的运算符“subscribe”只有以下方法:

所以我选择了json方法,但我从控制台获得了这些:

Response {_body: Object, status: 200, ok: true, statusText: "Ok", headers: Headers…}
function () {
        if (typeof this._body === 'string') {
            return JSON.parse(/** @type {?} */ (this._body));
        }
        if (this._body instanceof ArrayBuffer) {
            return …
我尝试了各种方法,但无法获得身体数据,除了这种奇怪的方法:

console.log(res._body.text);
当然,它有编译错误,但我确实得到了数据:

当我尝试使用AJAX时,上面所有的问题都没有出现,我可以很容易地得到这样的数据

jQuery(document).ready(function(){ 
    $.ajax({
         type: "get",
         async: false,
         url: "http://localhost:8080/",
         dataType: "jsonp",
         jsonp: "callback",
         jsonpCallback:"JSONP_CALLBACK",
         success: function(json){
             console.log(json.text);
         },
         error: function(){
             alert('fail');
         }
     });
 });

那么,如何使用Angular2中rxjs的可观察性获取json数据,或者这是一个bug?

您应该能够将响应映射为json:

this.jsonp.get("http://localhost:8080/callback=JSONP_CALLBACK")
  .map(res => res.json())
  .subscribe(data => console.log(data));

哦,天哪!非常感谢~~但是为什么我不能在订阅中执行“res.json()”?您可以:
.subscribe(res=>console.log(res.json())但将最终数据发送到订阅并在上一步中处理它会更干净。通常,最好将所有数据加载逻辑保留在服务中。返回可观察的实例。然后在组件中,您可以简单地调用服务方法并订阅它提供的任何数据。所以您不希望在组件中处理数据,而是希望使用它。但是在你的例子中,无论如何你都有这个调用组件,所以你当然可以跳过额外的映射步骤,直接在subscribe中使用
res.json()
。呃……我知道为什么我不能使用“res.json()”,因为我错过了“()”,T……太愚蠢了。再次感谢~~