如何使用服务在Angular中提交表单后更新列表

How to update list after submitting form in Angular with a service?

本文关键字:表单 更新 列表 提交 何使用 服务 Angular      更新时间:2023-09-26

我是Angular的新手,我正在尝试设置一个基本的"提交评论"&"显示评论列表"页面。我希望在提交评论后更新评论列表。目前我可以提交,但必须手动刷新页面才能看到。

控制器:

app.controller('FormController', function($scope, CommentService) {
    $scope.comment = {}; //will be populated by basic form
    $scope.submit = function() {
        return CommentService.post($scope.comment).then(function(){
            $scope.comment = ""; //blanks out form on POST
        });
    }
});
app.controller('CommentsController' function($scope, CommentService) {
    CommentService.list().then(function(comments){
        $scope.comments = comments.data;
    });
});

服务:

app.service('CommentService', function($http) {
    this.post = function(comment) {
        return $http.post('/api/v1/comments/', comment);
    };
    this.list = function() {
        return $http.get('/api/v1/comments/').
            success(function(data) {
                return data;
            });
    };
    //How do I connect the two controllers?
});

HTML表单/列表是超级通用的,我只使用"ng repeat"来显示注释。我在这里走对了吗?有什么简单的事情我可以做吗?当通过表格提交评论时,评论列表会更新?

提前感谢!

只要编辑语义以匹配程序,就可能做到这一点。

在您的控制器中:

var getList = function() {
    $scope.comments = CommentService.list();
};
CommentService.registerObserverCallback(getList);

为您服务:

var observerCallbacks = [];
// register the observer's callback in our callback list.
this.registerObserverCallback = function(callback){
  observerCallbacks.push(callback);
};
// function to notify our observers and call the callback they registered with
var notifyObservers = function(){
  angular.forEach(observerCallbacks, function(callback){
   callback();
 });
};
this.post = function(comment) {
    return $http.post('/api/v1/comments/', comment).success(function(data, status, headers, config) {
        notifyObservers();
    })
 };

所以基本上,你的控制器告诉你的服务,"嘿,我正在观察你……如果你做了什么,调用这个回调函数",并将其传递给getList。服务注册观察器,并在post()返回成功后调用回调。