使用Angular Resource查询具有字符串参数的REST API

Querying a REST API with a string parameter using Angular Resource

本文关键字:参数 REST API 字符串 Angular Resource 查询 使用      更新时间:2023-09-26

我正在尝试查询本地托管的REST API,这应该如下所示:

http://localhost:51608/api/UserRole?email=john@example.com

该请求有效,并返回一个具有AccessLevel属性的用户对象。现在我有了一个angular应用程序,并希望使用angular Resource查询该URL。我有如下内容,但URL没有正确构建。

(function () {
    "use strict";
    angular
        .module("common.services")
        .factory("userRoleResource",
                ["$resource",
                 "appSettings",
                    userRoleResource])
    function userRoleResource($resource, appSettings) {
        return $resource(appSettings.serverPath + "/api/UserRole:email", { email: '@email'});
    }
})();

我查询如下:

userRoleResource.query({ email: vm.userData.email },
   function (data) {
      vm.userData.accessLevel = data.AccessLevel;
});

但这产生的请求如下:

http://localhost:51608/api/UserRolejohn@example.com而不是http://localhost:51608/api/UserRole?email:john@example.com

这里怎么了?

根据$resource当前工作,它确实用您提供给$resource对象的电子邮件参数替换了:email。您可以在类似%3A 的地方对:进行编码

function userRoleResource($resource, appSettings) {
    return $resource(appSettings.serverPath + "/api/UserRole%3A:email", { email: '@email'});
}

为什么不将字符串格式化为:

return $resource(appSettings.serverPath + "/api/UserRole?email:" + email});