Angular - 基于 ID FK 链接表中的两个 API 源

Angular - link two API sources in table based on ID FK

本文关键字:两个 API 基于 ID FK 链接表 Angular      更新时间:2023-09-26

我真的是Angular的新手,我正在尝试创建一个用户事务列表,以显示操作时间和用户名。 在我的审计 API 中,我有一个操作 ID 和与我的用户 API 关联的用户 FK,我按如下方式显示它:

HTML
<table>
    <thead>
        <tr>                
            <th>
                Date/Time
            </th>
            <th>
                User
            </th>                
        </tr>
    </thead>
    <tbody>           
        <tr ng-repeat="audit in audit.data>
            <td>{{audit.audit_date_time}}</td>
            <td>**{{audit.audit_user_fk}}**</td>   **<--I need the name not the ID here**             
        </tr>            
    </tbody>
</table>

我的 API 如下:

AUDIT
[
    {
    "audit_id": "1",
    "audit_date_time": "2016-01-28 12:46:20",
    "audit_user_fk": "97"
    }
]
USER
[
    {
    "user_id": "97",
    "user_full_name": "Mr.User",        
    }
]

控制器,工作正常 GET来自每个 API 的数据:

app.controller('auditControl', ['$scope','auditService', 'userService', function ($scope, auditService, userService) {  
    var auditLogs = auditService.query(function () {
        $scope.audit.data = auditLogs;
    });
    var user = userService.query(function () {
        $scope.auditUser = user;
    });        
}]);

所以我遇到的主要问题是在表中获取用户名而不是外键值。 我已经删除了很多,以便我们可以专注于主要问题。 根据审核 API 中的 FK 从用户 API 获取用户名,并根据审核 API 中的项重复。

非常感谢任何帮助,并为菜鸟问题道歉!

创建自定义过滤器。

app.filter("lookupUser", function() {
    function lookup (idNum, userList) {
        var userName = "UNKNOWN";
        angular.forEach(userList, function(user) {
            if ( user.user_id == idNum ) {
                 userName = user.user_full_name;
            };
        });
        return userName;
    };
    return lookup;
});

然后在模板中:

    <tr ng-repeat="audit in audit.data>
        <td>{{audit.audit_date_time}}</td>
        <td>{{audit.audit_user_fk | lookupUser : auditUser }}</td>             
    </tr>            

你可以做这样的事情:

控制器:

app.controller('auditControl', ['$scope','auditService', 'userService', function ($scope, auditService, userService) {  
var auditLogs = auditService.query(function () {
    $scope.audit.data = auditLogs;
});
var user = userService.query(function () {
    $scope.auditUser = user;
});
$scope.getUserName = function (id) {
  var result = $scope.users.filter(function( user ) {
    return user.user_id == id;
  });
  if (angular.isDefined(result) && result.length > 0) {
    return result[0].user_full_name;
  } else {
    return "--";
  }
}
}]);

.HTML

<table>
<thead>
    <tr>                
        <th>
            Date/Time
        </th>
        <th>
            User
        </th>                
    </tr>
</thead>
<tbody>           
    <tr ng-repeat="audit in audit.data">
        <td>{{audit.audit_date_time}}</td>
        <td>**{{getUserName(audit.audit_user_fk)}}**</td>   **<--I need the name not the ID here**             
    </tr>            
</tbody>
</table>

我不知道用户数组在哪里,所以我打电话给$scope.users。