Angular使用旧版subscribe方法报错,求正确用法指导
问题解决:Angular中subscribe方法的正确使用
核心问题分析
- 无需手动调用
res.json():Angular 6+ 引入的HttpClient会自动将响应解析为JSON对象,再调用.json()会触发类型错误,这是你报错的直接原因。 - 回调函数的
this指向问题:直接传递this.Success和this.Error作为回调,会导致回调内部的this不指向组件实例,后续对组件属性的操作会失效。
修正后的代码
PosttoServer(){ var cusdto:any = {}; cusdto.CustomerCode = this.CustomerModel.CustomerCode; cusdto.CustomerName = this.CustomerModel.CustomerName; cusdto.CustomerAmount = this.CustomerModel.CustomerAmount; this.http.post("http://localhost:3000/posts", cusdto) .subscribe( // 箭头函数绑定组件实例的this (res) => { this.CustomerModels = res; // 直接使用已解析的响应对象 }, (error) => { console.debug(error); // 错误对象无需调用.json() } ); }
适配旧版Angular的补充说明
如果你的项目使用的是Http服务(Angular 5及更早版本),需要保留.json(),但必须修复this指向问题,可采用以下两种方式:
方式1:用bind(this)绑定上下文
PosttoServer(){ var cusdto:any = {}; cusdto.CustomerCode = this.CustomerModel.CustomerCode; cusdto.CustomerName = this.CustomerModel.CustomerName; cusdto.CustomerAmount = this.CustomerModel.CustomerAmount; this.http.post("http://localhost:3000/posts", cusdto) .subscribe(this.Success.bind(this), this.Error.bind(this)); } Success(res){ this.CustomerModels = res.json(); } Error(res){ console.debug(res.json()); }
方式2:箭头函数包裹回调
PosttoServer(){ var cusdto:any = {}; cusdto.CustomerCode = this.CustomerModel.CustomerCode; cusdto.CustomerName = this.CustomerModel.CustomerName; cusdto.CustomerAmount = this.CustomerModel.CustomerAmount; this.http.post("http://localhost:3000/posts", cusdto) .subscribe( res => this.Success(res), res => this.Error(res) ); } Success(res){ this.CustomerModels = res.json(); } Error(res){ console.debug(res.json()); }
内容的提问来源于stack exchange,提问作者Amit Tiwari
相关产品推荐
相关产品推荐

