1

I have a REST API that read/save data from a MongoDB database. The application I use retrieves a form and create an object (a job) from it, then save it to the DB. After the form, I have a button which click event triggers the saving function of my controller, then redirects to another url.

Once I click on the button, I am said that the job has well been added to the DB but the application is jammed and the redirection is never called. However, if I reload my application, I can see that the new "job" has well been added to the DB. What's wrong with this ??? Thanks !

Here is my code:

Sample html(jade) code:

button.btn.btn-large.btn-primary(type='submit', ng:click="save()") Create

Controller of the angular module:

function myJobOfferListCtrl($scope, $location, myJobs) {

    $scope.save = function() {
        var newJob = new myJobs($scope.job);
        newJob.$save(function(err) {
            if(err)
                console.log('Impossible to create new job');
            else {
                console.log('Ready to redirect');
                $location.path('/offers');
            }
        });     
    };    
}

Configuration of the angular module:

var myApp = angular.module('appProfile', ['ngResource']);

myApp.factory('myJobs',['$resource', function($resource) {
    return $resource('/api/allMyPostedJobs',
            {},
            {
                save: {
                    method: 'POST'
                }   
            });
}]);

The routing in my nodejs application :

app.post('/job', pass.ensureAuthenticated, jobOffers_routes.create);

And finally the controller of my REST API:

exports.create = function(req, res) {
    var user = req.user;
    var job = new Job({ user: user, 
                        title: req.body.title,
                        description: req.body.description,
                        salary: req.body.salary,
                        dueDate: new Date(req.body.dueDate),
                        category: req.body.category});
    job.save(function(err) {
        if(err) {
            console.log(err);
            res.redirect('/home');
        } 
        else {
            console.log('New job for user: ' + user.username + " has been posted."); //<--- Message displayed in the log    
            //res.redirect('/offers'); //<---- triggered but never render
            res.send(JSON.stringify(job));
        }
    });
};
4

1 回答 1

3

我终于找到了解决方案!问题出在屏幕后面 18 英寸处……

我像这样修改了角度应用程序控制器:

$scope.save = function() {
        var newJob = new myJobs($scope.job);
        newJob.$save(function(job) {
            if(!job) {
                $log.log('Impossible to create new job');
            }
            else {
                $window.location.href = '/offers';
            }
        });
    };    

诀窍是我的 REST api 将创建的作业作为 json 对象返回,我正在处理它,就像它是一个错误一样!因此,每次创建作业对象时,都会返回一个 json 对象,并且由于它不为空,因此会触发日志消息并且我从未被重定向。此外,我现在使用该$window.location.href属性来完全重新加载页面。

于 2013-10-10T18:10:54.747 回答