먼저 다음과 같은 코드로 spring-boot를 사용 하여 SERVER 를 코딩했습니다 .
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로 FRONT-END 를 코딩했습니다.
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…}
분명히 "_body : Object"에는 내가 원하는 데이터가 있으며 실제로 데이터는 다음과 같습니다.
{"text":"hello,world"}
그래서 나는 데이터를 얻으려고했지만 Observable의 연산자 "subscribe"는이 방법만을 가지고 있습니다 : 여기를 클릭하세요.
그래서 json 방법을 선택했지만 콘솔에서 다음을 얻었습니다.
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의 Observable을 사용하여 어떻게 json 데이터를 얻을 수 있습니까? 아니면 이것이 버그입니까?
응답을 JSON으로 매핑 할 수 있어야합니다.
this.jsonp.get("http://localhost:8080/callback=JSONP_CALLBACK")
.map(res => res.json())
.subscribe(data => console.log(data));
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다