2016-05-23 42 views
1

我正在嘗試使用我的服務插入每個捕獲的詳細信息頁面。angular.js - TypeError:無法讀取未定義的屬性'then'

雖然當我嘗試加載一個ID的頁面在我的服務(例如:/capture/5740c1eae324ae1f19b7fc30)我得到了一個未定義,使用此代碼:

app.factory('captureApi', ['$http', function($http){ 

var urlBase = 'URL'; 
// ==> Gives back an array as such: 
//[ 
//{ 
// "_id": "5740c1e3e324ae1f19b7fc2f", 
// "created_at": "2016-05-21T20:15:38.554Z", 
// "userId": "118000609287736585411", 
// "place": "place", 
// "birdname": "birdname", 
// "__v": 0 
//}, 
//{ 
// "_id": "5740c1eae324ae1f19b7fc30", 
// "created_at": "2016-05-21T20:15:38.554Z", 
// "userId": "118000609287736585411", 
// "place": "place", 
// "birdname": "birdname", 
// "__v": 0 
//}, 
//{ 
// ... 
//} 
//] 

return { 
    getAllCaptures : function() { 
     return $http.get(urlBase); 
    }, 

    insertCapture : function(data) { 
     return $http.post(urlBase, data); 
    }, 

    findCapture : function(id) { 
     //both give undefined 
     console.log(_.find(urlBase, function(capture){return capture._id == id})); 
     console.log(_.find(urlBase, function(capture){return capture.id == id})); 
     return _.find(urlBase, function(capture){return capture.id == id}); 
    } 
    } 
}]); 

在服務器端,我用的貓鼬/ MongoDB的:

-route:

var Capture = require('../models/capture'); 
module.exports = function(router) { 
    router.post('/captures', function(req, res){ 
     var capture = new Capture(); 
     capture.birdname = req.body.birdname; 
     capture.place = req.body.place; 
     capture.userId = req.body.userId; 
     capture.author = req.body.author; 
     capture.picture = req.body.picture; 
     capture.created_at = new Date(); 

     capture.save(function(err, data){ 
      if(err) 
       throw err; 
      console.log(req.body); 
      res.json(data); 
     }); 
    }); 

    router.get('/captures', function(req, res){ 
     Capture.find({}, function(err, data){ 
      res.json(data); 
     }); 
    }); 

    router.delete('/captures', function(req, res){ 
      Capture.remove({}, function(err){ 
       res.json({result: err ? 'error' : 'ok'}); 
      }); 
     }); 

    router.get('/captures/:id', function(req, res){ 
     Capture.findOne({_id: req.params.id}, function(err, data){ 
      res.json(data); 
     }); 
    }); 

    router.delete('/captures/:id', function(req, res){ 
     Capture.remove({_id: req.params.id}, function(err){ 
      res.json({result: err ? 'error' : 'ok'}); 
     }); 
    }); 

    // router.post('/captures/:id', function(req, res){ 
    //  Capture.findOne({_id: req.params.id}, function(err, data){ 
    //   var capture = data; 
    //   capture.birdname = req.body.birdname; 
    //   capture.place.city = req.body.place.city; 
    //   capture.place.country = req.body.place.country; 

    //   capture.save(function(err, data){ 
    //    if(err) 
    //     throw err; 
    //    res.json(data); 
    //   }); 
    //  }) 
    // }) 
} 

-model:

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 
var captureSchema = mongoose.Schema({ 
    birdname: {type: String, required: true}, 
    place: {type: String, required: true}, 
    userId: {type: String, required: true}, 
    author: {type: String, required: true}, 
    picture: Schema.Types.Mixed, 
    created_at: Date 
}); 

module.exports = mongoose.model('Capture', captureSchema) 

這裏是我的server.js(額外的信息):

// Init Express Web Framework 
var express = require('express'); 
var app = express(); 
var path = require('path'); 

// Set view engine to EJS & set views directory 
app.set('view engine', 'ejs'); 
app.set('views', path.resolve(__dirname, 'client', 'views')); 

app.use(express.static(path.resolve(__dirname, 'client'))); 

// Database Connection 
var mongoose = require('mongoose'); 
var configDB = require('./server/config/database.js'); 
mongoose.connect(configDB.url); 

var bodyParser = require('body-parser'); 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({extended: true}));    
app.use(bodyParser.text());          
app.use(bodyParser.json({ type: 'application/json'})); 

// Main route 
app.get('/', function(req, res){ 
    res.render('index.ejs'); 
}); 

// // catch 404 and forwarding to error handler 
// app.use(function(req, res, next) { 
//  var err = new Error('Not Found'); 
//  err.status = 404; 
//  next(err); 
// }); 

// API 
var api = express.Router(); 
require('./server/routes/capture')(api); 
app.use('/api', api); 

// Set routes to other pages 
app.get('/*', function(req, res){ 
    res.render('index.ejs'); 
}); 

// Port Settings 
app.listen(process.env.PORT || 3000, process.env.IP); 
console.log('Listening on port ' + process.env.PORT); 

在客戶端,我有以下觸發頁面:

$stateProvider 

    .state('home', { 
     url: '/', 
     templateUrl: 'partials/home.html', 
     controller: 'homeCtrl', 
     data: { 
      requiresLogin: false 
     }, 
     resolve: { 
      $title: function() { return 'Home'; } 
     } 
    }) 

    .state('dash', { 
     url: '/dashboard', 
     templateUrl: 'partials/dashboard.html', 
     controller: 'dashCtrl', 
     data: { 
      requiresLogin: true 
     }, 
     resolve: { 
      $title: function() { return 'Dashboard'; } 
     } 
    }) 

    .state('capture', { 
     url: '/capture', 
     templateUrl: 'partials/capture.html', 
     controller: 'captureCtrl', 
     data: { 
      requiresLogin: true 
     }, 
     resolve: { 
      $title: function() { return 'Capture'; } 
     } 
    }) 

    .state('viewCapture', { 
     url: '/capture/:id', 
     templateUrl: 'partials/viewCapture.html', 
     controller: 'viewCaptureCtrl', 
     data: { 
      requiresLogin: true 
     }, 
     resolve: { 
     $title: function() { return 'Capture Detail'; }   
     } 
    }) 

viewCaptureCtrl。 js:

app.controller('viewCaptureCtrl', ['$scope', 'captureApi', '$stateParams', '$http', function($scope, captureApi, $stateParams, $http) { 

    var id = $stateParams.id; 

     $scope.viewCapture = function() { 
     captureApi.findCapture(id) 
      .then(function(data) { 
       $scope.capture = data; 
      }); 
     }; 

     $scope.viewCapture(); 

}]); 

任何人都有一個想法,爲什麼我的查找功能給未定義? 非常感謝幫助!謝謝

+0

你確定'findCapture(id)'返回一個承諾嗎? – Kyle

+0

它是未定義的。我猜我的服務有問題,但無法弄清楚。 – Pex

回答

1

您需要參考underscoreJS並將其注入到您的服務中。文件:http://app-genesis.com/underscorejswithangularjs/

var app = angular.module("app", []); 
app.factory('_', function() { return window._; }); 

//inject into capture api factory 
app.factory('captureApi', ['$http', '_', function($http, _){ 
    //do stuff with _ 
}]); 

編輯:但我不熟悉_.find();如果它返回一個承諾或不。如果不是,您需要利用$q來創建一個承諾並返回,以便使用then()

//inject into capture api factory 
app.factory('captureApi', ['$http', '_', '$q', 
    function($http, _, $q) { 
     return { 
      findCapture: function(id) { 

       var deferred = $q.defer(); 

       try { 
        var results = _.find(); //do stuff with _ 
        deferred.resolve(results); 
       } catch (err) { 
        deferred.reject(err); 
       } 

       //you need to return a promise in order to use then() 
       return deferred.promise; 

      } 
     } 
    } 
]); 
+0

輸出仍然給出'未定義',但感謝已經可能需要在將來修復的東西.. – Pex

+0

@CedricBongaerts我不認爲'_.find()'返回一個承諾。你需要使用'$ q'。請參閱編輯。 – Kyle

+0

你的代碼給出了'錯誤:[$ injector:unpr]未知的提供者:,$ qProvider < - ,$ q < - captureApi' – Pex

相關問題