2017-11-21 2 views
1

HttpResponseクラスでのHttpResponseを使用するには(推奨されません)角度/ HTTP @のクラスResponseの置き換えです。ドキュメントを見ると、どこでどのように使用するのか、あまり考えられていません。さらに、古い角度コードを置き換えようとしましたが、このクラスは一般的なものなので、タイプは必要です。 HttpResponse<T>。それをタイプを与えることとしてエラーを与える:、どのように(角度/共通/ HTTP</strong> @<strong>に)angular2

Property 'json' does not exist on type 'HttpResponse<any>'

誰も私が角でのHttpResponseクラスを使用する方法を知って助けてくださいことはできますか?

UPDATE

これは私が作ったというのが私のコードスニペット、関数 'GET'、:ドキュメントごとなど

get(path: string, params: HttpParams = new HttpParams()): Observable<any> { 
    return this.http.get(`${environment.api_url}${path}`, { headers: this.setHeaders(), search: params }) 
    .catch(this.formatErrors) 
    .map((res: HttpResponse<any>) => res.json()); 
+1

私たちは、あなたがjson' 'に変換する必要はありません' HttpClient'モジュールを使用しているとき。応答はデフォルトでjsonに変換されます – Aravind

+0

これらのドキュメントを試しましたかhttps://angular.io/guide/http? httpコール – Alexander

+0

からコードを投稿できますか?@アレキサンダー:更新済み! –

答えて

1

HttpResponseは次のとおりです。

フルHTTPレスポンス型付きレスポンスボディ(返されなかった場合はnull)が含まれます。

HttpResponseは、応答イベントストリームで利用可能なHttpEventです。あなたが直面している特定の問題を1として

からTHttpResponsebody性質のために意味されるジェネリック型を指します。

class HttpResponse<T> extends HttpResponseBase { 
    constructor(init: {...}) 
    get body: T|null 
    ... 

あなたの変数がres: HttpResponse<any>であり、あなたがHttpResponseプロパティjsonを持っていないため動作しませんres.jsonようjsonプロパティにアクセスしようとしているので、場合。 bodyにアクセスしてからjsonにアクセスする必要があります。また

(res:HttpResponse<any>) => console.log(res.body.json) 

、あなたがHttpResponseを使用する良い例がHttpInterceptorです。インターセプタは、応答および/または要求イベントストリームを傍受および更新する。 HttpResponseHttpRequestで、event instanceofを使用して処理するストリームイベントを検出できます。ここで

はインターセプターの例である:

@Injectable() 
export class EmptyResponseInterceptor implements HttpInterceptor { 

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
    const newReq = req.clone({ 
     responseType: 'text' 
    }); 

    return next.handle(newReq).map((event: HttpEvent<any>) => { 
     if (event instanceof HttpResponse) { 
     let newEvent: HttpEvent<any>; 

     // alter response here. maybe do the following 
     newEvent = event.clone({ 
      // alter event params here 
     }); 

     return newEvent; 
     } 
    }); 
    } 
} 
関連する問題