关于Angular使用http发送请求后的响应处理
2023-09-14 09:04:02 时间
源代码:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
const ENDPOINT = "http://localhost:3000/echo?data=";
@Component({
selector: 'jerryform',
template: `
<input type="text" [formControl]="favoriteColorControl">
`
})
export class ReactFormComponent implements OnInit {
constructor(private http:HttpClient){
}
ngOnInit(): void {
this.favoriteColorControl.valueChanges.subscribe(
(value) =>{
console.log('new value: ' + value);
this.http.get('http://localhost:3000/angular/' + value).subscribe((response)=>console.log('response from http: ' + response),
(error)=>console.log('error: ' + error));
}
)
}
favoriteColorControl = new FormControl('');
}
nodejs实现的后台API代码:
app.route('/angular/*').get(
function(req, res){
var sResponse = 'Hello World';
var oResponse = {"success:":"ok"};
setTimeout( ()=>res.send(sResponse), 1000);
}
);
测试发现,这个HTTP请求在Chrome开发者工具里标注为成功:
然后我Angular代码里触发的是error handler,而不是期望中的success handler:
从错误明细能看出,Angular期望API返回的response是json结构:Unexpected token H in JSON at position 0
观察HTTP请求头部字段里的Accept:application/json:
返回一个json格式的response即可:
更多Jerry的原创文章,尽在:“汪子熙”:
相关文章
- Angular和Vue.js 深度对比
- Angular HTTPClient 发送请求的触发方式讨论
- 关于 Angular 部署以及 index.html 里 base hRef 属性的关联关系
- orbital angular momentum_omnidirectional
- Angular 应用开发里使用 ForRoot 解决 Lazy Loaded Module 里单例行为丢失的问题
- 【Angular教程】-组件通信|8月更文挑战
- 关于 Angular 工程文件 angular.json 里的 inlineCritical 属性
- Angular 应用里 ng-package.json 文件的作用是什么?
- Angular 应用 tsconfig.json 文件里的 typeRoots 属性讲解
- Angular 服务器端渲染场景里,服务器端和客户端渲染出的 HTML 源代码有可能不完全一致