gpt4 book ai didi

angularjs - Angular接收字符串作为数组?

转载 作者:行者123 更新时间:2023-12-04 14:00:04 24 4
gpt4 key购买 nike

我正在玩弄 AngularJS 和 ASP.Net 的 Web API 一起工作。我在 API 中有一个 TestController,它非常简单:

public class TestController : ApiController {
[HttpGet]
public String Ping() {
return "Pong";
}
}

在 Chrome 中,我可以转到 http://localhost/api/Test/Ping和 fiddler 显示一个简单的 "Pong"结果和浏览器显示:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Pong</string>

回到 Angular JS,我设置了一个工厂来调用 Ping 函数:
app.factory('API', ['$resource', function ($resource) {
return {
Ping: function () {
var result = $resource('api/Test/Ping', {}, { get: { method: 'GET' }, isArray: false });
return result.get();
}
};
}]);

还有一个 super 简单的 Controller :
app.controller('MyCtrl', [ '$scope', 'API', function ($scope, API) {
$scope.CallTest = function () {
API.Ping().$promise.then(function (response) {
alert(response);
});
}
}]);

当我单击 CallTest 的按钮时绑定(bind)到,它进行调用,API 像它应该返回的那样返回 Pong,但返回对象并不完全是我所期望的。响应是一个奇怪的对象:
{
0: """,
1: "P",
2: "o",
3: "n",
4: "g",
5: """,
$promise: {...},
$resolved: true
}

我没有收到任何错误,并且在语法上一切正常。然而,我希望 response将是一个字符串,特别是因为我设置了 isArray在我的 API 中为假工厂。我相信 angular 必须返回具有 $promise 的“资源”和 $resolved所以我现在明白它可能不会那样工作。除了在 WebAPI 中制作一个简单的包装器以在模型上返回字符串作为参数之外,还有可用的客户端选项,以便 response可以包含一个普通字符串而不是这个伪数组?可能像 response.data或者其他的东西?

编辑:当我从浏览器请求时, Accept标题包含:
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

这导致了上面的 XML 结果。当 Angular 请求相同的 url 时, Accept标题包含:
application/json, text/plain, */*

这导致响应的内容只是 "Pong"

最佳答案

如文档中所述,$resource是一个工厂,它创建一个资源对象,让您与 RESTful 服务器端数据源进行交互。

在您的情况下,您并没有尝试与正确的 RESTful 数据源进行交互,因此这种行为看起来很奇怪。

在您拥有适当的 RESTful 数据源并且您只想访问 API 端点并检索一个简单的响应(例如字符串)之前,您应该使用 $http service :

$http.get('api/Test/Ping').success(function (data) {...})...

例如。:
app.factory('API', ['$http', function ($http) {
return {
Ping: function () {
return $http.get('api/Test/Ping');
}
};
}]);

app.controller('MyCtrl', ['$scope', 'API', function ($scope, API) {
$scope.CallTest = function () {
API.Ping().success(function (data) {
alert(data);
});
};
}]);

关于angularjs - Angular接收字符串作为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25771273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com