First, I coded the SERVER using spring-boot, code like these:
首先,我用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);
}}
Second, I coded the FRONT-END with Angular2:
第二,我用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);
);
}}
then, I run the front-end in ng-serve, and got the infomation from console:
然后,我在ng服务中运行前端,并从控制台获得信息:
Response {_body: Object, status: 200, ok: true, statusText: "Ok", headers: Headers…}
obviously, the "_body: Object" has the data I want, and in actual, the data looks like:
显然,“_body: Object”有我想要的数据,在实际中,数据看起来是这样的:
{"text":"hello,world"}
so i tried to get the data, but Observable's operator "subscribe" only has these method: click here
所以我试着获取数据,但可观察的操作员“订阅”只有这些方法:点击这里。
so i selected the json method, but i got these from console:
所以我选择了json方法,但是我从控制台得到这些:
function () {
if (typeof this._body === 'string') {
return JSON.parse(/** @type {?} */ (this._body));
}
if (this._body instanceof ArrayBuffer) {
return …
I had tried every method, but cannot get the body data, except this weird approach:
我试过了所有方法,但都无法得到身体数据,除了这个奇怪的方法:
console.log(res._body.text);
of course, it has compile error, but I do get the data:click here
当然,它有编译错误,但我确实得到了数据:点击这里。
All the problems above are not appeared when I tried this by using AJAX, I can easily get the data like this
当我使用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');
}
});
});
So, how can I get the json data with rxjs's Observable in Angular2, or is this a bug?
那么,如何在Angular2中使用rxjs的可观察值来获取json数据呢,或者这是一个bug?
1 个解决方案
#1
1
You should just be able to map response as JSON:
您应该能够将响应映射为JSON:
this.jsonp.get("http://localhost:8080/callback=JSONP_CALLBACK")
.map(res => res.json())
.subscribe(data => console.log(data));
#1
1
You should just be able to map response as JSON:
您应该能够将响应映射为JSON:
this.jsonp.get("http://localhost:8080/callback=JSONP_CALLBACK")
.map(res => res.json())
.subscribe(data => console.log(data));