我必须向这个API发送动态数据,这个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不接受动态值?任何帮助都是可以接受的
发布于 2017-10-29 20:26:02
如果将this.params附加到string中,则需要在options对象中设置:
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]"
https://stackoverflow.com/questions/47004833
复制相似问题