【问题标题】:express and angularJs $location.path not redirecting to /express 和 angularJs $location.path 没有重定向到 /
【发布时间】:2014-08-03 09:52:52
【问题描述】:

这是我在 app.js 文件中的 AngularJs 代码

 var CarApp = angular.module('CarApp',['ngResource'])

 CarApp.config(function($routeProvider){
    $routeProvider
       .when('/',{controller:ListCtrl,templateUrl:'partials/list.html'})
       .when('/edit/:id',{controller:EditCtrl,templateUrl:'partials/details.html'})
       .otherwise({redirectTo:'/'})

  });

  // to map update method
  CarApp.factory('CarsService',function($resource){
       return $resource('/api/cars/:id',{id:'@_id'} , {update:{method:'PUT'}})
  });

  function EditCtrl($scope,$location,$routeParams,CarsService){

 var id = $routeParams.id;

 //console.log(id);

 CarsService.get({id: id},function(resp){
    $scope.car = resp;

 });

 // Update Page title
 $scope.action = "Update";

  $scope.save = function() {
     CarsService.update({id:id},$scope.car,function(){
        $location.path('/')
     });
  }
}

这是我的 Express server.js 代码

   var express = require('express');
   var http = require('http');
   var path = require('path');
   var cars = require('./server/api/cars.js')

   var app = express();

   var client_dir =  path.join(__dirname, '/client')

   // all environments
    app.set('port', process.env.PORT || 3000);
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(app.router);
    app.use(express.static(client_dir));
    app.use(express.static(path.join(__dirname, '/image')));


    app.get('/', function(req,res){
       res.sendfile(path.join(client_dir,'index.html'))

    });

    // ordering is important to for angularJs to differentiate between list all  and read

    app.get('/api/cars',cars.list);

    app.get('/api/cars/:id',cars.read);
    app.post('/api/cars/',cars.create);
    app.put('/api/cars/:id',cars.update);
    app.del('/api/cars/:id',cars.delete);

    http.createServer(app).listen(app.get('port'), function(){
       console.log('Express server listening on port ' + app.get('port'));
    });

这是我的 details.html 代码

   <h2>{{action}} Ferrari</h2>

  <form name="carform" class="form-horizontal">

      <div class="control-group">
           <label class="control-label" for="year">Year</label>
           <div class="controls">
              <input type="text" ng-model="car.year" id="year" name="year" placeholder="">
           </div>
      </div>

<div class="form-actions">
    <button ng-click="save()" class="btn btn-primary">
        Update
       </button>
      <a href="/" class="btn">Cancel</a>
   </div>
 </form>

这是我的 mongodb 后端服务

 function update(req,res){

var newCarData = req.body;
var id = req.params.id;

newCarData._id = ObjectId(id);
updateCar(newCarData,function(err){
     if(err) throw new Error("unable to update");

     else{
        res.json();
     }
  });
}


 function updateCar(car,callback){
    db.collection(collectionName,function(error,collection){
        if(error) callback(true);

        else {
            collection.save(car,function(){
                //console.log("updated data")  ;
            });

        }
    });
  }

我面临的问题是当我按下 details.html 中的更新按钮时,我可以更新我的 mongodb 后端服务中的详细信息。

在控制台中调用了 put 方法,但我无法在 angularJs app.js 中使用 $location.path('/') 重定向到“/”路径文件 ?任何帮助将不胜感激。

【问题讨论】:

  • 你试图在 put 方法的回调中放置一个参数,如下所示: $scope.save = function() { CarsService.update({id:id},$scope.car,function (resp){ $location.path('/') }); }
  • 是添加了参数 resp ,没有运气仍然无法正常工作

标签: javascript node.js mongodb angularjs express


【解决方案1】:

根据docs,$location 在浏览器 URL 更改时不会导致整个页面重新加载。要在更改 URL 后重新加载页面,请使用较低级别的 API,$window.location.href。

【讨论】:

  • $window.location.href('/') 仍然没有重定向
  • 你试过纯Javascriptlocation.href吗?如果这不起作用,那是你在其他地方遇到了问题。
  • 请帮帮我,我无法重定向?我应该把整个源代码邮寄给你吗..
  • 在网络检查器中,我看到 put api/cars 挂起,但数据库正在更新
  • @shaunak1111 $window.location.href 是属性而不是方法。使用它的正确方法是这样的; $window.location.href = '/'; 。请参阅此相关 Stackoverflow 问题的答案stackoverflow.com/questions/7077770/…
【解决方案2】:

您需要创建一个控制器 ListCtrl,即使它没有任何内容。 您的网络检查器中可能有一个错误,提示它找不到 ListCtrl。

【讨论】:

    【解决方案3】:

    看起来在你的 updateCar 函数中,你没有在成功尝试时调用你的回调:

    function updateCar(car,callback){
      db.collection(collectionName,function(error,collection){
        if(error) callback(true);
    
        else {
            collection.save(car,function(){
                //console.log("updated data")  ;
                callback(null, { ok: true }); //something like this.
            });
    
        }
      });
    }
    

    因此,您在调用 location.path 的编辑 ctrl 中的回调从未被调用过。 :D

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-17
      • 2017-04-10
      • 1970-01-01
      • 2012-09-07
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 2017-11-01
      相关资源
      最近更新 更多