与对象的URL连接在Angular 4中返回错误请求

时间:2017-10-29 20:20:29

标签: angular http

我必须将动态数据发送到此API,它只有两个必需的参数:id和text。我有一个对象,这些键绑定到视图中的输入并且id被编码,但是当我提交时,我得到400状态代码:

观点:

<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不接受动态值?任何帮助都会产生很大的影响

1 个答案:

答案 0 :(得分:1)

您要将this.params附加到字符串,您需要在选项对象中设置它:

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 => {...});

或者您可以手动构建所需的网址:

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]"