无法在 Angular 1 应用程序中设置对变量的 api 调用结果
我正在尝试调用 api,并将结果设置为变量。当我将其记录在控制台中时,我能够成功进行调用并查看数据,但后来当我尝试使用该变量时,它是未定义的。
这是相关代码:
var postParams = {
"code": input.Code,
"number": input.Number
}
var result;
try {
$http.post("/api/DetailAPI/GetDetails?code=" + input.Code + "&number=" + input.Number, postParams).success(function (details) {
console.log(details);
result = JSON.parse(details);
});
}
catch (error) {
console.log(error);
}
console.log(result);
第一个 console.log(details) 显示我期望列为“对象”的数据。当调用 console.log(result) 时,结果是未定义的。
我尝试过使用和不使用 JSON.parse() 并得到相同的结果。
我知道 api 调用正在工作,因为我可以在控制台中看到数据。问题是我无法将此数据存储在结果变量中。
如何让 Angular 真正将从 api 调用获得的数据放入变量中?
I am trying to call an api, and set the results to a variable. I am able to successfully make the call and see the data when I log it in the console, but later when I try to use the variable it is undefined.
Here is the relevant code:
var postParams = {
"code": input.Code,
"number": input.Number
}
var result;
try {
$http.post("/api/DetailAPI/GetDetails?code=" + input.Code + "&number=" + input.Number, postParams).success(function (details) {
console.log(details);
result = JSON.parse(details);
});
}
catch (error) {
console.log(error);
}
console.log(result);
The first console.log(details) shows the data I am expecting listed as "Object". When console.log(result) is called result is undefined.
I have tried with and without JSON.parse() and get the same result either way.
I know the api call is working, since I can see the data in the console. The issue is that I cannot store this data in my result variable.
How do I get Angular to actually put the data I get from the api call into a variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在定义结果变量之前对其进行安慰。
You are consoling the result variable before it has been defined.