2017-10-29 6 views
1

IDとテキストの2つの必須パラメータを持つこのAPIに動的データを送信する必要があります。私は、ビュー内の入力とidにバインドさこれらのキーを持つオブジェクトがharcodedされていますが、私が提出したときに、私は400のステータスコードを取得する:オブジェクトとのURL連結が不正なリクエストを返す4

ビュー:

<form novalidate #f="ngForm" (submit)="onSubmit(f);" > 
    <mat-form-field> 
    <textarea matInput placeholder="Text" 
    id="output-text" 
    name="text" 
    [(ngModel)]="params.text" 
    #userName="ngModel" 
    placeholder="text" 
    minlength="2" 
    required> 
    </textarea> 
    </mat-form-field> 

    <button type="submit" value="Submit" class="block" (click)="onSubmit(f)" mat-raised-button>Submit</button> 

</form> 

TS:

//INTERFACE 
    results: response; 

    //PARAMS 

params = { 
    "handwriting_id": "8X3WQ4D800B0", 
    "text": "", 
    "handwriting_size": "", 
    "handwriting_color": "", 
    } 

    constructor(private http: HttpClient) { } 

    ngOnInit() { 
    } 

    onSubmit(f){ 

     this.http.get<Response>('https://api.handwriting.io/render/png?' + this.params ,{ 
     headers: new HttpHeaders().set('Authorization', 'Basic ' + 
     btoa('STRSKVENJVBD0JDS:4ZN6VD256FEBHSM1')) 
     }).subscribe(data => { 
     this.results = data['results']; 
     console.log(data); 

     },(err: HttpErrorResponse) => { 
      if (err.error instanceof Error) { 
      console.log('An error occurred:', err.error.message); 
      } else { 
      console.log(`Backend returned code ${err.status}, body was: ${err.error}`); 
      } 
     }); 
    } 

しかし、私はURLをハードコーディングすると、次のように:

https://api.handwriting.io/render/png?handwriting_id=8X3WQ4D800B0&text=test 

私はここで何かが欠けてる200を取得します。 APIが動的な値を受け入れない理由すべてのヘルプは非常にあなたが文字列にthis.paramsを追加している

答えて

1

をapreciatedだろう、あなたはオプションでそれを設定する必要があるオブジェクト:

this.http.get<Response>('https://api.handwriting.io/render/png', { 
    params: new HttpParams().set('handwriting_id', params.handwriting_id).set('text', params.text), 
    headers: new HttpHeaders().set('Authorization', 'Basic ' + btoa('STRSKVENJVBD0JDS:4ZN6VD256FEBHSM1')) 
}).subscribe(data => {...}); 

それとも、手動であなたが望むURL構築することができ:

const url = `https://api.handwriting.io/render/png?handwriting_id=${params.handwriting_id}&text=${params.text}`; 

this.http.get<Response>(url, { 
    headers: new HttpHeaders().set('Authorization', 'Basic ' + btoa('STRSKVENJVBD0JDS:4ZN6VD256FEBHSM1')) 
}).subscribe(data => {...}); 

が問題あなたのアプローチではJSで文字列にオブジェクトを追加しようとすると"[object Object]"に変換されますので、このURLへのリクエストをしています:

"https://api.handwriting.io/render/png?[object Object]"

+0

@MartinAdámekの回答に感謝しますが、私は 'this.params'に下線を引いています。 Intellisenseは、このタイプ(params)には型パラメータと共通のプロッタタイがないと言います。パラメータ:Codec – Mellville

+0

今すぐ試してみてください。 'HttpParams'は私が思ったものとは異なるAPIを持っています。それは '新しいHttpHeaders()。(キー、値)'を設定する必要があります –

+0

@マーティンAdámekありがとう、それは "マニュアルURL"と働いた。乾杯! – Mellville

関連する問題