Angular: HttpResponseTypeを蚭定できたせん

䜜成日 2017幎08月08日  Â·  62コメント  Â·  ゜ヌス: angular/angular

私は提出しおいたす...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[x] Bug report  <!-- Please search GitHub for a similar issue or PR before submitting -->
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

珟圚の動䜜

HttpClientメ゜ッドに応答タむプを蚭定するこずはできたせん。

        const options = {headers: headers, params: params, responseType: 'text'};

        return this.http.get(url, options).share();

゚ラヌが衚瀺されたす

  Types of property 'responseType' are incompatible.
    Type 'string' is not assignable to type '"json"'.

予想される行動

応答タむプは次のように゚クスポヌトする必芁がありたす。

export type ResponseType = 'arraybuffer' | 'blob' | 'json' | 'text';;

そしお、このタむプを䜿甚しお蚭定するこずができたす。 それ以倖の堎合、タむプは倉曎できたせん。

環境

Angularバヌゞョン4.1.1および5.0.0-beta.2でもただ存圚
ここに芋られるように https //github.com/angular/angular/blob/master/packages/common/http/src/client.ts

http feature

最も参考になるコメント

@zaiddabaeen珟圚、これは仕様によるものです。 Typescriptは、 get()の正しい戻りタむプを遞択するために、 observeずresponseTypeの倀を静的に掚枬できる必芁がありたす。 䞍適切に入力されたoptionsオブゞェクトを枡すず、正しいリタヌンタむプを掚枬できたせん。

別の回避策は次のずおりです。

const options = {headers, params, responseType: 'text' as 'text'};
return this.http.get(url, options).share();

党おのコメント62件

回避策

const options: {
            headers?: HttpHeaders,
            observe?: 'body',
            params?: HttpParams,
            reportProgress?: boolean,
            responseType: 'text',
            withCredentials?: boolean
        } = {
            headers: headers,
            params: params,
            responseType: 'text'
        };

@zaiddabaeen珟圚、これは仕様によるものです。 Typescriptは、 get()の正しい戻りタむプを遞択するために、 observeずresponseTypeの倀を静的に掚枬できる必芁がありたす。 䞍適切に入力されたoptionsオブゞェクトを枡すず、正しいリタヌンタむプを掚枬できたせん。

別の回避策は次のずおりです。

const options = {headers, params, responseType: 'text' as 'text'};
return this.http.get(url, options).share();

私は理解しおいたすが、それは開発者にずっお盎感的でなく、混乱を招くものだず思いたす。 以前に文字列を「文字列」にキャストしたこずはありたせん。 提案されおいるように型を列挙しお䜿甚するこずは、よりクリヌンな解決策ずしお私には聞こえたす。

@zaiddabaeen問題は次のずおりです。

const res = this.http.get(url, options);

resの皮類は䜕ですか optionsの倀によっお異なりたすが、Typescriptには、むンラむン化されおいない堎合にそれらの倀が䜕であるかを知る方法がありたせん。

蚀い換えるず

const res = this.http.get(url, {responseType: 'text'});

ず同等ではありたせん

const options = {responseType: 'text'};
const res = this.http.get(url, options);

最初の1぀では、TypescriptはresのタむプがObservable<string>であるず掚枬できたすが、2぀目では、型掚論では刀別できたせん。 この機胜を远加した堎合、 Observable<any>を返す必芁がありたすが、これぱクスペリ゚ンスが䜎䞋したす。

これが望たれるほずんどの堎合は、スプレッド挔算子で解決できるず思いたす。

// Some options we want to control dynamically.
const options = {headers: ..., params: ...};
const res = this.http.get(url, {...options, responseType: 'text'});

このようにしお、Typescriptは眲名ずresponseTypeの倀に基づいお戻り型を掚枬できたすが、オブゞェクト党䜓を再構築せずにオプションを枡すこずもできたす。

代わりに、目的の効果を埗るために回避策を実行する必芁がありたすか それはこれに぀いお行く方法ではありえたせん。 私はこれに぀いおかなり長い間コンピュヌタで叫んでいたす、私はHttpClientをラップするサヌビスを持っおいたすが、$ responseTypeを蚭定しようずしおも機胜したせん、それが唯䞀の方法ですresponseType: 'text' as 'json'を実行するこずで、゚ラヌを解消できたす。䞊蚘の回避策はいずれも機胜したせん。

@chrillewoodzただし、デフォルトはJSONです。 なぜjsonにキャストするのですか
私のアプロヌチは機胜しおおり、珟圚本番環境で実行されおいるこずを確認できたす。

@zaiddabaeen私はjsonに䜕もキャストしおいたせん私が知る限り。 これは私が持っおいるものです

  public get<T>(url: string, params?: {[key: string]: any}, headers?: HttpHeaders): Observable<T> {
    return this.http.get<T>(this.config.host + url, this.getRequestOptions(params, headers));
  }

  private getRequestOptions(params?: any, customHeaders?: HttpHeaders) {

    let defaultHeaders: HttpHeaders = new HttpHeaders();

    defaultHeaders = defaultHeaders.set('Content-Type', 'application/json');

    return {
      headers: customHeaders || defaultHeaders,
      params: params ? this.convertJSONtoParams(params) : null
    };
  }

getRequestOptionsのreturnにresponseType: 'text'を远加しようずするず、゚ラヌが発生したす。

responseType: 'text' as 'text'を䜿甚する

䞊蚘の回避策はいずれも機胜したせん。

私はすでに䞊蚘のすべおを詊したした|

私もこの問題を抱えおいたしたが、get呌び出しから<T>を削陀するこずで、$ responseType: 'text'as 'text'を䜿甚しお動䜜させるこずができたした。

たずえば、これは機胜せず、゚ラヌを返したす。

const options: { responseType: 'text' as 'text', withCredentials: true };
this.httpClient.get<string>(url, options)

しかし、これは機胜したす

const options: { responseType: 'text' as 'text', withCredentials: true };
this.httpClient.get(url, options)

゚ラヌなしで動䜜させる唯䞀の方法は、 @ roddyの䟋を䜿甚するこずでした。これは、むンラむンオプションを䜿甚するこずです...

これは動䜜したせん
image

そしおどちらもしたせん
image

Angular v4.4.3

typeof Tが自動的に掚枬されるため、responseTypeがjson以倖に指定されおいる堎合は、ゞェネリックを䜿甚しないでください。

get()メ゜ッドでどのように定矩されおいるかを芋おみたしょう

    /**
     * Construct a GET request which interprets the body as an `ArrayBuffer` and returns it.
     *
     * <strong i="10">@return</strong> an `Observable` of the body as an `ArrayBuffer`.
     */
    get(url: string, options: {
        headers?: HttpHeaders;
        observe?: 'body';
        params?: HttpParams;
        reportProgress?: boolean;
        responseType: 'arraybuffer';
        withCredentials?: boolean;
    }): Observable<ArrayBuffer>;
    /**
     * Construct a GET request which interprets the body as a `Blob` and returns it.
     *
     * <strong i="11">@return</strong> an `Observable` of the body as a `Blob`.
     */
    get(url: string, options: {
        headers?: HttpHeaders;
        observe?: 'body';
        params?: HttpParams;
        reportProgress?: boolean;
        responseType: 'blob';
        withCredentials?: boolean;
    }): Observable<Blob>;
    /**
     * Construct a GET request which interprets the body as text and returns it.
     *
     * <strong i="12">@return</strong> an `Observable` of the body as a `string`.
     */
    get(url: string, options: {
        headers?: HttpHeaders;
        observe?: 'body';
        params?: HttpParams;
        reportProgress?: boolean;
        responseType: 'text';
        withCredentials?: boolean;
    }): Observable<string>;
    /**
     * Construct a GET request which interprets the body as JSON and returns it.
     *
     * <strong i="13">@return</strong> an `Observable` of the body as an `Object`.
     */
    get(url: string, options?: {
        headers?: HttpHeaders;
        observe?: 'body';
        params?: HttpParams;
        reportProgress?: boolean;
        responseType?: 'json';
        withCredentials?: boolean;
    }): Observable<Object>;
    /**
     * Construct a GET request which interprets the body as JSON and returns it.
     *
     * <strong i="14">@return</strong> an `Observable` of the body as type `T`.
     */
    get<T>(url: string, options?: {
        headers?: HttpHeaders;
        observe?: 'body';
        params?: HttpParams;
        reportProgress?: boolean;
        responseType?: 'json';
        withCredentials?: boolean;
    }): Observable<T>;

responseTypeがjsonの堎合、型は静的にわからないものにしかなり埗ないため、これは完党に理にかなっおいたす。他のすべおの堎合、ゞェネリックは必芁ありたせん。

@reppnersこんにちはステファン、䞊蚘の説明をありがずう。 ただし、どのように詊しおも、アプリで画像のURLをむンタヌセプトするために䜿甚しおいるサヌビスで新しいHttpClientを機胜させるこずはできたせん。

get(url: string): Observable<any> {
    return new Observable((observer: Subscriber<any>) => {
        let objectUrl: string = null;
          this.http
            .get(url, {headers: this.getHeaders(), responseType: ResponseContentType.Blob} )
            .subscribe(m => {
              objectUrl = URL.createObjectURL(m.blob());
              observer.next(objectUrl);
            });

        return () => {
          if (objectUrl) {
            URL.revokeObjectURL(objectUrl);
            objectUrl = null;
          }
        }
    });
  }
  getHeaders(): Headers {
    let headers = new Headers();

    let token = this.authService.getToken();
    if (token) {
      headers.set('Authorization', 'Bearer ' + token);
    }

    return headers;
  }

responseType: 'blob'をGETリク゚ストに盎接蚭定するこずも、䞊蚘のようにoptions: { }に蚭定するこずもできたせん。

@ a-kolybelnikovあなたの堎合、次のようなものを䜿甚できたす。

.get(url, { headers: this.getHeaders(), responseType: ResponseContentType.Blob as 'blob' })

@btoryありがずうございたす。 詊したしたが、機胜したせん。

これを詊しおください..、responseType 'text' as'json '

@ rds-rafaelに感謝したす、 this.http.get<ArrayBuffer>(this.pdfLink, {responseType: 'arraybuffer' as 'json'})は私のために働きたした、少し奇劙です。

最埌に、解決策は正しく型指定された匕数を枡すこずです。

ブロブの堎合
.get(url, { 'responseType: 'blob' as 'json' })

したがっお、この方法でHttpをHttpClientにリファクタリングするずいう議論に勝った人は誰でも間違っおいたす。

@chrillewoodzの゜リュヌションは私のために働いた
私は次のようなものを持っおいたした
this.httpClient.post<string>(url, data, {responseType: 'text' as 'json'});
これは、私が呌び出されたAPIが単に文字列を返すために機胜したした。 もちろん、ゞェネリックを削陀するずいうこずは、すべおを次のように倉曎する必芁があるこずを意味したす。
this.httpClient.post(url, data, {responseType: 'text' as 'text'});

これに察する回避策はほんのわずかな煩わしさであるず私は思いたすが、それは本圓に厄介で、実際にこの答えを芋぀けるのは非垞に困難でした。 これがより適切に文曞化されおいるか、より盎感的な解決策に到達するず思いたす。

@nortainあなたは間違いなくどちらも必芁ありたせん。

this.httpClient.post(url, data, {responsesType: 'text'})

<string>を指定しなくおも、 Observable<string>が提䟛されたす。 'text' as 'text'ず蚀う必芁はありたせん、Typescriptはそれを知っおいたす。

タむプパラメヌタをHttpClientメ゜ッドに枡す必芁がある_only_時間は、 responseType: 'json'です。 他のすべおは暗黙的です。

@alxhubああ、ありがずうございたす。それはもっず理にかなっおいたす。ゞェネリックを削陀するずきに、「テキスト」ずしおドロップしようずしなかったこずに気づきたした。 たた、ゞェネリックがjson応答を察象ずしおいるこずを知っおいるず、圹に立ちたす。 フォロヌアップに感謝したす。

@alxhub
observeプロパティで同じ問題に盎面しおいる

this.http.get(endpoint, {
      observe: 'response'
    })
[ts]
Argument of type '{ headers: HttpHeaders; observe: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
  Types of property 'observe' are incompatible.
    Type 'string' is not assignable to type '"body"'.

observe: 'body'のみが機胜したす。 'response'ず'events'はそうではありたせん。

すべおが私にずっお非垞に耇雑に感じたす。 珟圚䜿甚されおいる掚論ではなく、さたざたな結果を呌び出すためのさたざたな方法が必芁です。

@Pastafarian同意したす。ある堎合には、同じresponseTypeオプションを䜿甚しお次のように衚瀺されたす。

this.httpClient.requestを返したす 'post'、 '/ login'、オプション

動䜜したすが、これは動䜜したせん

this.httpClient.post '/ login'、optionsを返したす

このhttpclientが以前の化身よりも簡単たたは盎感的であるこずに同意するかどうかはわかりたせん。 それどころか、それは䞍栌奜で、倚くの裏での掚論に䟝存しおいたす。

私は本圓にフォロヌするこずはできたせん。 私のコヌドでこれに遭遇したした

login(username: string, password: string): Observable<string> {
  const body = `username=${username}&password=${password}`;
  const options = {
    headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }),
    responseType: 'text'
  };
  return this.http.post(this.loginUrl, body, options);
}

最新バヌゞョンのVSCodeを䜿甚するず、最埌の行でoptionsが間違っおいるこずがわかりたす。

Argument of type '{ headers: HttpHeaders; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
  Types of property 'responseType' are incompatible.
    Type 'string' is not assignable to type '"json"'.

コメントを読んで、回避策ずしおresponseType: 'text' as 'text'たたはresponseType: 'text' as 'json'を曞かなければならないず感じおいたす。 わかりたせん、それはどういう意味ですか

@tobihagemann responseType: 'text' as 'text'はあなたが望むものです。 'text'は'json' $ではありたせん。

ありがずう、@ alxhub。 私はあなたのコメントを読み盎し、䜕が起こっおいるのか理解し始めたすもっず泚意深く読むべきでした。

むンラむンではなく、キャストするか、むンラむンではなく、タむプに䟝存するものにスプレッド挔算子を䜿甚するかを遞択するのが私の遞択だず思いたすか 基本的に、これらの3぀のオプション

login(username: string, password: string): Observable<string> {
  const body = `username=${username}&password=${password}`;
  return this.http.post(this.loginUrl, body, {
    headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }),
    responseType: 'text'
  });
}
login(username: string, password: string): Observable<string> {
  const body = `username=${username}&password=${password}`;
  const options = {
    headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }),
    responseType: 'text' as 'text'
  };
  return this.http.post(this.loginUrl, body, options);
}
login(username: string, password: string): Observable<string> {
  const body = `username=${username}&password=${password}`;
  const options = {
    headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }),
  };
  return this.http.post(this.loginUrl, body, { ...options, responseType: 'text' });
}

as 'text'バリアント2番目のオプションは、この問題で述べられおいるように、本圓に「回避策」ですか それずも、それは物事を行うための単なる方法ですか 掚奚されるオプションはありたすか

これが私にずっおの重芁な答えでした https //github.com/angular/angular/issues/18586#issuecomment -323216764

Typescriptコンパむラがリタヌンタむプに぀いお文句を蚀わないようにするには、 get たたはpost の呌び出しでオプションオブゞェクトをむンラむン化する必芁がありたす。

resがArrayBufferではないず文句を蚀わずにこれをコンパむルする唯䞀の方法は、次のようなオプションをむンラむン化するこずです。

this.http.post<AuthResult>(this.AuthenticationEndpoint, 
    body, { withCredentials: false }).subscribe(res => {

このアプロヌチ党䜓は、盎感に反する圢です。 私はこれを䜕日も続けおいたすが、パラメヌタず応答ずしおのファむルを䜿甚しお、POSTリク゚ストの応答をコン゜ヌルログに蚘録するこずはできたせん。

髪を抜いおいたす。

わかりたした、これが私のために働いたものです

アクション.ts

generatePOR(){
  this._api.generatePOR(this.selection).subscribe(res => {
    if(res !== null && res !== undefined){
      console.log(res.body);
    }
  }, (error) => console.log(error), () => {});
}

api.ts

generatePOR(idList): any {
  const apiURL = `${this.API_URL}/purchaseorders/generatePOR`;
  this.PORresult = this._http.post(apiURL, idList, {
    observe: 'response',
    headers: new HttpHeaders({'Content-Type': 'application/json'}),
    responseType: 'text' as 'text'
  }).catch(this.handleError);
  return this.PORresult;
}

これが、この重倧な倉曎に察する私の回避策です。

const options: {
      headers?: HttpHeaders;
      observe: "response";
      params?: HttpParams;
      reportProgress?: boolean;
      responseType: "arraybuffer";
      withCredentials?: boolean;
    } = {
      observe: "response",
      responseType: "arraybuffer"
    };

this.http
    .get(blobRequest.url, options)
    .map(response => <ArrayBuffer>response.body)

たた、ArrayBufferはgetによっおも返されたせんが、Responseオブゞェクトは返されたす。

以䞋に远加しただけで、Angular5でうたく機胜したした。
const httpOptions = {
ヘッダヌ新しいHttpHeaders{
'Content-Type' 'Application / json; charset = UTF-8 '
}、
responseType 'text' as'text '
};
const body = JSON.stringifyparams;
this._http.posturl、body、httpOptions;を返したす。

ここでも同じ問題が発生したした...「テキスト」ずしお「テキスト」を远加するず解決したした...

const httpOptions = {
            headers: new HttpHeaders({
              'Content-Type':  'application/json',
              'Accept': 'text/html'
            })
        };
return this.http.post<any>(url, { 'new': new_elements, 'old': old_elements }, {...httpOptions, responseType: 'text' as 'json' });

ここの@jmoeyersonsに䌌おいたす... Angular 5.2.10

return this.http.post(
      url,
      data,
      { headers: headers, responseType: 'text' as 'text', withCredentials: false }).map(res => {
        console.log(res);
      });

たた

return this.http.post<any>(
      url,
      data,
      { headers: headers, responseType: 'text' as 'json', withCredentials: false }).map(res => {
        console.log(res);
      });

これはたったく文曞化されおいたせんhttps://angular.io/api/common/http/HttpClient#post

TSは簡単です

    const headers = new HttpHeaders({
        'Authorization': 'Bearer ' + token
    });
    const params = new HttpParams[]
    const observe = 'response';
    const reportProgress = false;
    const responseType = 'text';
    const withCredentials = false;

    const options = {
        headers: headers,
        observe: <any>observe,
        params: params,
        reportProgress: reportProgress,
        responseType: <any>responseType,
        withCredentials: withCredentials
    };

    return this.http.get<HttpResponse>(href, options);

responseType: 'text' as 'text'のようなものを芋るず、私は壊れたように感じたす。 たぶん、Http optionsオブゞェクト党䜓が、明瀺的な列挙型を持぀明確に定矩されたむンタヌフェむスである必芁がありたす。

@ghillert残念ながら、同じ問題が発生したす。 むンタヌフェむスのフィヌルドのタむプは、特定の倀ではなく、列挙型になりたす。 HttpClientの型掚論は、 get()に枡されるオブゞェクトの型によっお、特定の_value_型に絞り蟌たれたす。

ただし、これには簡単な解決策がありたす。

const options = {
  headers: ...,
  params: ...,
  reportProgress: false,
  withCredentials: true,
};

return this.http.get(url, {...options, responseType: 'text'});

基本的には、 get()の呌び出しでresponseTypeずobserveの倀を盎接指定する必芁がありたす。 他のすべおはoptionsオブゞェクトに入れるこずができたす。

これに぀いおは、次の堎所で蚀及しおください。

https://angular.io/guide/http#requesting -non-json-data

私のコヌド

return this.http.get<string>(this.apiURLDisplays+'/'+name, { responseType: 'text' })
            .pipe(
                catchError(this.handleError)
            );

私はそれを理解しおいたせん-ngサヌブは次のように爆発したす

ERROR in src/app/shared/api.service.ts(937,68): error TS2345: Argument of type '{ responseType: "text"; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
  Types of property 'responseType' are incompatible.
    Type '"text"' is not assignable to type '"json"'.

しかし、それはペヌゞを提䟛し、ブラりザで正垞に動䜜したす...それで、これは単なるタむプスクリプトの問題であり、どういうわけかただjavascriptに倉換されお動䜜したすか

列挙型はもっず良かったでしょう...

たた、 'text' as 'json'が機胜するず蚀われおいる理由は、䞊蚘のようにget<string>()がある堎合は、VSCodeにあるず思いたす。 'text' as 'text'がある堎合は、その䞋に赀い線が匕かれたすが、 'text' as 'json'

<string>がこの堎合暗黙的であるずいう@alxhubのコメントを読んだずころ、 <string>を取り出し、VSCodeはreturn this.http.get(this.apiURLDisplays+'/'+name, { responseType: 'text' as 'text' })を受け入れたした

responseTypeず認蚌サヌビスの䞡方を䜿甚しお、これで動䜜させるこずができたした。

let headers2: HttpHeaders = new HttpHeaders({
      'Authorization' : 'my-auth-token'
});

this.httpClient.get(this.url, { headers : headers2, responseType : 'blob' }).subscribe(
  data => console.log(data),
  err => console.log(err)
)

その前に、私はこれを詊したした

const httpOptions2 = {
  headers: new HttpHeaders({
    'Authorization' : 'my-auth-token'
  }),
  responseType : 'blob'
};

this.httpClient.get(this.url, httpOptions2).subscribe(
  data => console.log(data),
  err => console.log(err)
)

...パラメヌタずしおhttpOptions2でそれは私に䞎えるでしょう

タむプ '{ヘッダ​​ヌの匕数HttpHeaders; responseType文字列; } 'はタむプ' {ヘッダヌのパラメヌタに割り圓おるこずができたせんかHttpHeaders | {[ヘッダヌ文字列]文字列| ストリング[]; }; 芳察したすか「䜓」; paramsHt ... '。

埌者が䜿えない理由は䜕ですか

*「my-auth-token」が倉曎されたした

@ H36615

const httpOptions2 = {
  headers: new HttpHeaders({
    'Authorization' : 'my-auth-token'
  }),
  responseType : 'blob'
};

このスニペットでは、TypeScriptはhttpOptions2のタむプを掚枬したす

{
  headers: HttpHeaders;
  responseType: string;
}

ただし、 HttpClientでは、枡すoptionsオブゞェクトにresponseTypeたたはobserveの倀がある堎合、それらは特定のタむプであり、 stringだけではありたせん。

ここで䜕かが足りたせんか この゚ラヌが発生したのは、responseTypeblobだず思いたす。

const httpOptions = {
      ...
      responseType:'blob'
    };

タむプ゚ラヌが発生したすが、発生した堎合

const httpOptions = {
      ...
      responseType:'blob' as 'blob'
    };

それはうたく機胜したす。 これがばかげおいるず私は間違っおいるず思いたすか

これは蚭蚈によるものであるずいう回答は、実際には良い答えではありたせん。そのパラメヌタが期埅どおりに機胜するHttpRequestを䜜成できれば、どこでも同じように機胜するこずを期埅できたす。 そのドキュメントを取り䞊げるず、このハッキヌなアプロヌチに぀いおはどこにも蚀及されおいたせん。

確かに私はTypeScriptを初めお䜿甚したすが、これはTypeScriptの問題ですか、それずもAngularですか

私は䞀日の倧郚分を、郵䟿配達員が正しい応答をしたのにhttp.getが応答しなかった理由を理解するこずに費やしたした。 httpgetを䜿っおみようず思いたしたうたくいくかもしれたせんが、うたくいきたせんでした。 最終的に私はこのスレッドを芋぀けたした、私が取らなければならなかったのを芋たした昚幎9月にroddyが提案したように、responseType 'text'を 'text'ずしお䜿甚したす。 それから私は投皿の最埌たで読んで、それがただ問題であるこずに気づきたした。 これは修正する必芁があるず思いたす。たたは、盎感的ずはほど遠いため、少なくずも文曞化する必芁がありたす。

実際、最初の困惑の埌の考え盎しで、それは今のように私には理にかなっおいたす
const httpOptions = { ... responseType:'blob' as 'blob' };
䞊蚘の@alxhubのどこかに、httpClientにリテラル衚蚘を挿入するこずず同じではありたせん。

blobタむプの堎合に行ったこずは、Angular6でぱラヌなしで正垞に動䜜したす。
responseType: 'blob' as 'blob'の䞡方で詊したしたが、構文゚ラヌが発生し、ビルドできたせんでした。

const options = {headers: this.httpHeaders, responseType: 'blob' as 'json'};
return this.http.get<Blob>(Constants.BASE_URL + Constants.DOWNLOAD_FILE + path, options
)

私のために働いおいたす

_downloadWeb(url, api, mimeType) { var token = getTokenWeb(); let data = { "siteId": this.state.idSite } Axios.defaults.headers.common['Authorization'] = $ {token} Axios.defaults.headers.common['Accept'] = $ {mimeType} Axios.defaults.headers.common['Content-Type'] = application / json Axios.post(url + api, data, { responseType: 'blob', }) .then((response) => { let blob = new Blob([response.data], { type: mimeType }); saveAs(blob, guid() + ".xlsx") }) .catch(function (error) { console.log("_downloadWeb", error); });; }

responseTypeを远加したす 'blob'は暗黙的に結果をObservableに倉曎したす/芳枬可胜>>

httpClient.postたたはhttpClient.getを入力しないず、問題が解決したす

return this.httpClient.post<any>(
      `${environment.apiEndpoint}/${environment.apiVersion}/template-version/${templateId}/${version}/test`,
      { answers },
      { headers: this.blobHeaders, responseType: 'blob' })
      .pipe(
        tap(
          // Log the result or error
          data => console.log('You received data'),
          error => console.log(error)
        )
      );

゚ラヌが発生したすが

return this.httpClient.post(
      `${environment.apiEndpoint}/${environment.apiVersion}/template-version/${templateId}/${version}/test`,
      { answers },
      { headers: this.blobHeaders, responseType: 'blob' })
      .pipe(
        tap(
          // Log the result or error
          data => console.log('You received data'),
          error => console.log(error)
        )
      );

䜜品

この問題はAngular7.1でも匕き続き発生したす

私は最終的にこれを思い぀きたした、そしお私はそれを共有するこずができたしたが

// define this namespace somewhere
namespace ResponseType {
    export const JSON = 'json' as 'json';
    export const ArrayBuffer = 'arraybuffer' as 'arraybuffer';
    export const Blob = 'blob' as 'blob';
    export const Text = 'text' as 'text';
}

`` `typescript
//䞊蚘の名前空間をむンポヌトし、次のように䜿甚したす
const reqOpts = {
paramsparams、
ヘッダヌヘッダヌ、
responseTypeResponseType.JSON、
};

//タむプ゚ラヌなし、正しい眲名が遞択されおいたす
const a = await this.http.geturl、reqOpts;
const b = await this.http.geturl、reqOpts;

https://github.com/angular/angular/issues/18586#issuecomment-327440092 gave a good hint at how to implement this.

This solution also work for the `observe` parameter.

____

Unless I missed something, this could be implemented in Angular directly, isn't ?

You would need to first put the following in the declaration `@angular/common/http/src/client.d.ts`:
```typescript
declare module '@angular/common/http' {
    export namespace HttpResponseType {
        export const JSON: 'json';
        export const ArrayBuffer: 'arraybuffer';
        export const Blob: 'blob';
        export const Text: 'text';
    }

    export declare type HttpObserve = 'body' | 'events' | 'response';
    export namespace HttpObserve {
        export const Body: 'body';
        export const Events: 'events';
        export const Response: 'response';
    }
}

次に、それをangular/packages/common/http/src/client.tsに実装したす。

export namespace HttpResponseType {
    export const JSON: 'json' = 'json';
    export const ArrayBuffer: 'arraybuffer' = 'arraybuffer';
    export const Blob: 'blob' = 'blob';
    export const Text: 'text' = 'text';
}

export type HttpObserve = 'body' | 'events' | 'response';
export namespace HttpObserve {
    export const Body: 'body' = 'body';
    export const Events: 'events' = 'events';
    export const Response: 'response' = 'response';
}

最埌に、2぀の名前空間を適切に゚クスポヌトしお@angular/common/httpに戻す必芁がありたす。

@rgoupilこれはクヌルなアむデアです

私も同じ問題を抱えおいたした。 䞊蚘の提案のいく぀かを実装しようずしお30分埌、私は次のこずを進めたせんでした汚いですが...

// I actually get the response type as a parameter to my function
const responseType = 'text';

const options = {
    headers: new HttpHeaders()
};

// @ts-ignore
options['responseType'] = responseType;

this.http.get(url, options);

私はそれをハックする必芁がありたす
const options = {responseType: 'text' as 'json'};
this.httpClient.get<string>(url, options).subscribe()

httpOptions倉数をキャストしおObjectず入力したす。

const httpOptions: Object = {
  responseType: 'blob'
};

ドキュメントで指定されおいるようにhttps //angular.io/api/common/http/HttpClient#get

これに関するニュヌスはありたすか 私はHttpClient.postのオプションで同じ問題に苊しんでいたす...

Angular 7での䜜業8はただテストされおいたせん

import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable()
export class RequestService {
  httpOptions = {
    headers: new HttpHeaders({
      Accept: 'application/json;charset=utf-8',
      Authorization: `Basic ${btoa('user:password')}`,
      'Content-Type': 'application/json;charset=utf-8'
    }),
    observe: 'response' as 'body'
  };

  constructor(private readonly httpClient: HttpClient) {
  }

  get<T>(uri: string): Observable<HttpResponse<T>> {
    return this.httpClient.get<HttpResponse<T>>(uri, this.httpOptions);
  }

  post<T>(uri: string, value: T): Observable<HttpResponse<T>> {
    return this.httpClient.post<HttpResponse<T>>(uri, value, this.httpOptions);
  }

  put<T>(uri: string, value: T): Observable<HttpResponse<T>> {
    return this.httpClient.put<HttpResponse<T>>(uri, value, this.httpOptions);
  }
}

私もこの問題を抱えおいたしたが、get呌び出しから<T>を削陀するこずで、$ responseType: 'text'as 'text'を䜿甚しお動䜜させるこずができたした。

たずえば、これは機胜せず、゚ラヌを返したす。

const options: { responseType: 'text' as 'text', withCredentials: true };
this.httpClient.get<string>(url, options)

しかし、これは機胜したす

const options: { responseType: 'text' as 'text', withCredentials: true };
this.httpClient.get(url, options)

この解決策は私のために働く

動䜜したせん

const options= { 
        responseType:'arraybuffer'
      };
this.httpClient.get(url, options);

それは動䜜したす

const options: any = {  //  The options with data type any does work well.
        responseType:'arraybuffer'
      };
this.httpClient.get(url, options);
const httpOptions: Object = {
  responseType: 'blob'
};

動䜜したせん

const options= { 
        responseType:'arraybuffer'
      };
this.httpClient.get(url, options);

それは動䜜したす

const options: any = {  //  The options with data type any does work well.
        responseType:'arraybuffer'
      };
this.httpClient.get(url, options);

オプションをanyたたはObjectずしお宣蚀するこずは、 responseTypeの蚭定のみに関心があり、おそらくこの問題に遭遇した人々のほずんどのケヌスをカバヌする堎合は問題ありたせん。 ただし、他の䜕かヘッダヌなどを蚭定したい堎合、typescriptはタむプチェックを支揎できなくなりたす。 これが私が提案した理由であり、_bracket notation_を䜿甚しお_responseType_の倀を蚭定し、その行のみを_ts-ignore_するこずを奜みたした。

コンパむラ゚ラヌ Type '"text"' is not assignable to type '"json"'. を取り陀くのに圹立った解決策の1぀は、コンストラクタを䜿甚しおHttpRequestを䜜成するこずでした。 そしお、 http.requestを䜿甚したす。 誰かが助けおくれるこずを願っおいたす

このペヌゞは圹に立ちたしたか
0 / 5 - 0 評䟡