javascript - Angular:在 AJAX 成功时设置变量
问题描述
我正在开发一个小型应用程序,并且一直在玩 angular。单击我正在调用 ajax 获取请求的按钮时,我遇到了这个问题。在 ajax 成功时,我想为给定的结果设置一个变量。但问题是没有设置变量。我的代码如下...
export class HomePageComponent implements OnInit {
apiEndpoint = "myapiendpoint";
searchQuery = "";
searchResult = {};
constructor() {}
onSearchSubmit(e) {
e.preventDefault();
let queryUrl = this.apiEndpoint + this.searchQuery;
$.ajax({
url: queryUrl,
dataType: "json",
method: "GET",
success: function(res) {
this.searchResult = res;
},
error: function() {
console.log("Error");
}
});
}
ngOnInit() {}
}
当我尝试设置变量 searchResult 它没有设置但是当我控制台直接在成功回调中记录响应时,它会在控制台中给我整个响应。我究竟做错了什么?
谢谢
解决方案
当您this
在函数中使用关键字时,它将指向成功函数的范围而不是外部范围,因此它不会更新外部范围变量。这个问题有两种解决方案
1.使用箭头功能:
$.ajax({
url: queryUrl,
dataType: "json",
method: "GET",
success: (res)=>{
this.searchResult = res;
},
error: function() {
console.log("Error");
}
});
}
由于箭头函数没有自己的范围。this
在箭头函数中总是指向外部函数。
2.将外部复制this
到变量之一,然后使用该变量而不是this
:
将this
外部函数复制到一个变量中,然后在 ajax 成功函数中使用该变量,在这种情况下this
将指向正确的上下文
像下面
export class HomePageComponent implements OnInit {
apiEndpoint = "myapiendpoint";
searchQuery = "";
searchResult = {};
var that=this; // Copied this into that variable
constructor() {}
onSearchSubmit(e) {
e.preventDefault();
let queryUrl = this.apiEndpoint + this.searchQuery;
$.ajax({
url: queryUrl,
dataType: "json",
method: "GET",
success: function(res) {
that.searchResult = res;// use that instead of this
},
error: function() {
console.log("Error");
}
});
}
ngOnInit() {}
}
使用上述解决方案之一,它将解决您的问题
推荐阅读
- javascript - 如何使用 {flip: false} 退出“rtl”?
- android - 从未填充的意图中为 Editext 设置文本
- asp.net-core - Automapper:“缺少类型映射配置或不支持的映射。”
- python - 按条件检索时间行。让代码在一天内工作
- python-3.x - Picamera http流叠加静态图片
- macos - AppKit 如何决定是否将窗口的标题和工具栏呈现为灰色,这是可配置的吗?
- css - 为什么 CSS text-align:center; 不行?
- arduino - 测试 Arduino WiFiServer 消息
- xamarin - 如何使用 xamarin.forms pcl 或将其转换为 xamarin native
- python - 根据xml标签标题获取文本