2017-03-20 1 views
0

webservice에서 반환 된 json을 얻기 위해 angular2 typeScript를 사용하고 있습니다. get을 호출하면 WebService에서 값을 얻을 수 있지만 JSON의 구성 요소를 가져올 수 없습니다. 예를 들어 싶습니다. 반환 된 JSON의 상태를 가져옵니다. 전체 JSON을 얻을 수 있지만 JSON의 정확한 상태는 얻을 수 없습니다. 아래 webservice에서 반환 한 샘플 코드와 JSON을 볼 수 있습니다.JSON의 구성 요소를 얻는 방법 webservice 요청으로 반환하는 문자열

감사 Alper

샘플 코드 :

this.http.get(this.webServiceUrlGet) 
    .subscribe(
    function (data) { 
     this.tradeShows = JSON.stringify(data); 
     console.log(this.tradeShows); 

    }, 
    error => this.errorMessage = <any>error); 

    JSON : 
    "_body":"{\n \"args\": {}, \n \"headers\": {\n \"Accept\":  \"application/json, text/plain, */*\", \n \"Accept-Encoding\": \"gzip, deflate, sdch, br\", \n \"Accept-Language\": \"tr-TR,tr;q=0.8,en-US;q=0.6,en;q=0.4\", \n \"Connect-Time\": \"0\", \n \"Connection\": \"close\", \n \"Host\": \"httpbin.org\", \n \"Origin\": \"http://localhost:3000\", \n \"Referer\": \"http://localhost:3000/navigation\", \n \"Total-Route-Time\": \"0\", \n \"User-Agent\": \"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36\", \n \"Via\": \"1.1 vegur\", \n \"X-Request-Id\": \"db6c93bd-99dd-4410-a709-5bc2dd4150fb\"\n }, \n \"origin\": \"212.175.18.38\", \n \"url\": \"https://httpbin.org/get\"\n}\n","status":200,"ok":true,"statusText":"OK","headers":{"Content-Type":["application/json"]},"type":2,"url":"https://httpbin.org/get"} 
+0

때문에 resp.json()를 호출 할 필요가;' –

+0

전에 시도했지만 정의되지 않은 sachilla 알려줍니다. – user2307786

+1

'JSON.parse (response)'가 필요하다. 귀하의 경우에 '데이터' –

답변

1

그냥 이렇게 :

this.tradeShows = data.json();

구독 할 때 다시는 HTTP 호출로부터 얻을 목적은 HTTP의 모든 측면에 대한 정보를 가지고있는 Response 객체이다 headers, body 등을 포함한 호출. json() 메서드는 자동으로 본문 필드를 가져 와서 사용할 수있는 객체로 바꿉니다.

그런데 JSON.stringify()은 개체를 가져 와서 문자열로 변환합니다. 수동 JSON 구문 분석을 수행하려는 경우 JSON.parse()을 사용해야합니다.

당신이 HTTP 상태 코드는 응답의 상태 속성에 해당 액세스 할 수 있습니다 다시 전송 얻고 싶은 경우에 : data.status

+0

그는 내가 이해하는대로 http 상태를 원합니다. – n00dl3

+0

감사합니다. 제시. data.json(). userId가 내 문제를 해결했다고 말했듯이. 건배 – user2307786

+0

np, 도움이 된 것을 기쁘게 생각합니다. –

-1

타이프 라이터를 사용하는 동안 당신은 API에

서비스 호출을 값을 매핑하고, 예를 들어 구성 요소 페이지에서 가입이 필요

import { Http, Response, Headers, RequestOptions, URLSearchParams } from "@angular/http"; 
constructor(
     private authHttp: Http) {} 
let url= `this.webServiceUrlGet`; 
     let params = new URLSearchParams; 
     params.append('id', id); 
    return this.authHttp.post(url, { headers:headers, search:params }) 
    .map(res => res.json()); 

구성 요소

this.service.get(this.id) 
       .subscribe(
       res => this.item= res, 
       error => this.errorMessage = error 
       ); 
+0

그것은 typescript와는 관련이 없지만 각형 Http 서비스와 관련이 있습니다. 백킹으로'this.webServiceUrlGet'을 둘러싸는 이유는 무엇입니까? 왜 OP 코드를 기반으로 사용하지 않는가? (예 :'authHttp' 서비스 대신'Http')? – n00dl3

+0

그게 내 'authHttp'객체의 HTTP에서 할당 된 –

+0

안녕하세요 Venkateswaran 나는 타입 스크립트의 솔루션이 필요합니다 형제 – user2307786

1

당신이 은 JSON이 작업을 수행 할 수있는 상태를 확인하려면 다음

this.http.get(this.webServiceUrlGet) 
    .map(resp=>[resp.status,resp.json()]) 
    .subscribe(([status,data]) => { 
     this.tradeShows = data; 
     this.status = status; 
     console.log(this.tradeShows,this.status); 
    }, 
    error => this.errorMessage = <any>error); 

당신은 당신`을 console.log (this.tradeShows.status)를 사용하지 않는 이유는 무엇 HTTP 서비스에 의해 전송되는 것은 Response object

+1

결과를 왜 문자열링하겠습니까? OP의 인공물 인 –

+0

을 삭제했습니다. – n00dl3

관련 문제