404 when deleting a mongo document via express, mongoose, and angular - angularjs

I'm new to using the MEAN stack, have learned some of the basics to add data to mongodb using mongoose, express, and ui-router. However, I can't figure out how to delete a document. Whenever I try, I get 404 errors, even though it looks like the link should be correct. Would someone please help? Be kind, my code might be way off...
Here is my angular file:
var app = angular.module('updateTracker', ['ui.router']);
app.factory('courses', ['$http', function($http){
var o = {
courses: []
};
o.getAll = function() {
return $http.get('/courses').success(function(data){
angular.copy(data, o.courses);
});
};
o.create = function(course) {
return $http.post('/courses', course).success(function(data){
o.courses.push(data);
});
};
o.get = function(id) {
return $http.get('/courses/' + id).then(function(res){
return res.data;
});
};
o.addEntry = function(id, entry) {
return $http.post('/courses/' + id + '/entries', entry);
};
o.changeLesson = function(course) {
return $http.put('/courses/' + course._id + '/changeLesson')
.success(function(data){
course.lesson = "New Lesson";
});
};
o.removeCourse = function(course) {
return $http.delete('/courses/' + course._id + '/removeCourse')
.success(function (data, status) {
console.log(data);
});
};
return o;
}]);
app.controller('MainCtrl', [
'$scope',
'courses',
function($scope, courses){
$scope.courses = courses.courses;
$scope.addCourse = function(){
if(!$scope.lesson || $scope.lesson === '') { return; }
courses.create({
lesson: $scope.lesson,
course: $scope.course,
curriculum: $scope.curriculum
});
$scope.lesson = '';
$scope.course = '';
$scope.curriculum = '';
};
$scope.changeLesson = function(course){
courses.changeLesson(course);
};
$scope.removeCourse = function(course) {
courses.removeCourse(course);
};
}]);
app.controller('CoursesCtrl', [
'$scope',
'courses',
'course',
function($scope, courses, course){
$scope.course = course;
$scope.addEntry = function(){
// if($scope.version === '') { return; }
courses.addEntry(course._id, {
version: $scope.version,
notes: $scope.notes,
statusCode: $scope.statusCode,
statusMessage: $scope.statusMessage,
author: 'user'
}).success(function(entry) {
$scope.course.entries.push(entry);
});
$scope.version = '';
$scope.notes = '';
$scope.statusCode = '';
$scope.statusMessage = '';
};
}]);
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
resolve: {
postPromise: ['courses', function(courses){
return courses.getAll();
}]
}
})
.state('courses', {
url: '/courses/{id}',
templateUrl: '/courses.html',
controller: 'CoursesCtrl',
resolve: {
course: ['$stateParams', 'courses', function($stateParams, courses) {
return courses.get($stateParams.id);
}]
}
});
$urlRouterProvider.otherwise('home')
}]);
My routes:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Course = mongoose.model('Course');
var Entry = mongoose.model('Entry');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
router.get('/courses', function(req, res, next) {
Course.find(function(err, courses) {
if(err){ return next(err); }
res.json(courses);
});
});
router.post('/courses', function(req, res, next) {
var course = new Course(req.body);
course.save(function(err, course) {
if(err){return next(err); }
res.json(course);
});
});
router.param('course', function(req, res, next, id) {
var query = Course.findById(id);
query.exec(function (err, course){
if (err) { return next(err); }
if (!course) { return next(new Error('can\'t find course')); }
req.course = course;
return next();
});
});
router.get('/courses/:course', function(req, res, next) {
req.course.populate('entries', function(err, course) {
if (err) { return next(err); }
res.json(course);
});
});
router.post('/courses/:course/entries', function(req, res, next) {
var entry = new Entry(req.body);
entry.course = req.course;
entry.save(function(err, entry){
if(err){ return next(err); }
req.course.entries.push(entry);
req.course.save(function(err, course) {
if(err){ return next(err); }
res.json(entry);
});
});
});
router.put('/courses/:course/changeLesson', function(req, res, next) {
req.course.changeLesson(function(err, course){
if (err) { return next(err); }
res.json(course);
});
});
router.delete('courses/:course', function(req, res) {
Course.remove({
_id : mongodb.ObjectID(req.params.course)
}, function(err) {
if(err) { res.send(err);}
console.log("remove id");
})
});
router.param('entry', function(req, res, next, id) {
var query = Entry.findById(id);
query.exec(function (err, entry){
if (err) { return next(err); }
if (!entry) { return next(new Error('can\'t find entry')); }
req.entry = entry;
return next();
});
});
and my course Schema:
var mongoose = require('mongoose');
var CourseSchema = new mongoose.Schema({
lesson: String,
course: String,
curriculum: String,
entries: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Entry'}]
});
CourseSchema.methods.changeLesson = function(cb) {
this.lesson = "Update Lesson";
this.save(cb);
};
mongoose.model('Course', CourseSchema);

You forgot to add / in the begining of router.delete and /removeCourse at end as well as did not return value using either res.send or res.json or res.end, etc. This should be like bellow
router.delete('/courses/:course/removeCourse', function(req, res) {
Course.remove({
_id : req.params.course
}, function(err) {
if(err) {
console.log(err);
res.status(500).send(err);
} else {
res.json({});
console.log("remove id");
}
})
});

Related

Ionic Local Storage - save $http database to device

I'm having some troubles with the local storage and my Ionic app. The thing is quite straight forward - I would like to store to device all the data from from sql database and then display it when the device is without network.
So the code where I get my data from looks like this:
controllers.js:
$http.get('http://someurl.php?type=json')
.success(function(data) {
$scope.info = data;
})
.error(function(response) {
$scope.info = "Error";
});
So can anyone help me out with this one?
Thank you!
I can suggest to you to use some plugin for DB but with localstorage you have to pass (and install) this:
angular-local-storage
and then use it in your JS like:
$http.get('http://someurl.php?type=json')
.success(function(data) {
//test if is online or offline and the do something
if($rootScope.isOnLine)
localStorageService.set("nameofkey", { data:data }); //here you store in your localstorage ... remeber to inject it as dependency
$scope.info = data;
})
.error(function(response) {
$scope.info = "Error";
});
then if you want to know if your ionic app is online or offline you can use this plugin: http://ngcordova.com/docs/plugins/network/
"use strict";
// Ionic Starter App
angular.module("myapp", ["ionic",
"ionic.service.core",
"ngCordova",
"ionic.service.push",
"ngResource",
"LocalStorageModule",
"ionic-native-transitions",
"angularMoment"])
.run(["$ionicPlatform", "authService", "$rootScope", "$timeout", "$cordovaSpinnerDialog", "$window", "$cordovaNetwork", "$state", "ScanService", "$cordovaToast", "localStorageService", "DB",
function ($ionicPlatform, authService, $rootScope, $timeout, $cordovaSpinnerDialog, $window, $cordovaNetwork, $state, ScanService, $cordovaToast, localStorageService, DB) {
$ionicPlatform.ready(function () {
$rootScope.isOnLine = true;
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (ionic.Platform.isIPad() &&
window.cordova &&
window.cordova.plugins &&
window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
// CONNECTION STATE /////////////////////////////////////////////
if ($cordovaNetwork) {
//listen for OnLine event
$rootScope.$on('$cordovaNetwork:online', function (event, networkState) {
var onlineState = networkState;
$rootScope.isOnLine = true;
});
// listen for Offline event
$rootScope.$on('$cordovaNetwork:offline', function (event, networkState) {
var offlineState = networkState;
$rootScope.isOnLine = false;
});
}
//////////////////////////////////////////////////////////////////
});
}]);
This is an exmaple for a Service using it for call http or from local if there is no connection:
"use strict";
angular
.module('gestione')
.factory("ScanService", ["$q", "$resource", "enviroment", "$rootScope", "localStorageService", "DB",
function ($q, $resource, enviroment, $rootScope, localStorageService, DB) {
var self = this;
// Private Fileds
var _serviceBase = "api/Scan/";
var _serviceBaseBarScan = "api/BarScan/";
var _serviceBaseCount = "api/Scan/Count";
var _serviceBaseLast = "api/Scan/Last";
var _serviceBaseAll = "api/Scan/All";
// Private Method
var _resource = $resource(enviroment.apiUrl + _serviceBase, { skip: '#skip', take: '#take' }, {
query: { method: "GET", isArray: true },
create: { method: "POST", isArray: false }
});
var _resourceLast = $resource(enviroment.apiUrl + _serviceBaseLast, {}, {
query: { method: "GET", isArray: false }
});
var _resourceAll = $resource(enviroment.apiUrl + _serviceBaseAll, {}, {
create: { method: "POST", isArray: true }
});
var _resourceCount = $resource(enviroment.apiUrl + _serviceBaseCount, {}, {
query: { method: "GET", isArray: false }
});
var _resourceBar = $resource(enviroment.apiUrl + _serviceBaseBarScan, {}, {
query: { method: "GET", isArray: true },
create: { method: "POST", isArray: false }
});
return {
Get: function (skip, take) {
var deferred = $q.defer();
// IS ONLINE
if ($rootScope.isOnLine) {
_resource.query({ skip, take }).$promise.then(function (resp) {
deferred.resolve(resp);
}).catch(function (err) {
deferred.reject(err);
});
} else { // OffLine
DB.Query("SELECT * FROM Scan ORDER BY ROWID DESC ;").then(function (result) {
var scan = DB.fetchAll(result);
deferred.resolve(scan);
}, function (err) {
deferred.reject(err);
});
}
return deferred.promise;
},
GetLast: function () {
var deferred = $q.defer();
// IS ONLINE
if ($rootScope.isOnLine) {
_resourceLast.query().$promise.then(function (resp) {
deferred.resolve(resp);
}).catch(function (err) {
deferred.reject(err);
});
} else { // OffLine
DB.Query("SELECT * FROM Scan ORDER BY ROWID DESC LIMIT 1 ;").then(function (result) {
var scan = DB.fetch(result);
deferred.resolve(scan);
}, function (err) {
deferred.reject(err);
});
}
return deferred.promise;
},
GetNotSync: function () {
return DB.Query("SELECT * FROM Scan WHERE sync = ? ", ['false']).then(function (result) {
return DB.fetchAll(result);
});
},
CheckInOrOut: function (item) {
return DB.Query("SELECT * FROM Scan WHERE idTicket = ? ORDER BY ROWID DESC LIMIT 1;", [item.IdTicket]).then(function (result) {
return DB.fetch(result);
});
},
Count: function () {
var deferred = $q.defer();
// IS ONLINE
if ($rootScope.isOnLine) {
_resourceCount.query().$promise.then(function (resp) {
deferred.resolve(resp);
}).catch(function (err) {
deferred.reject(err);
});
} else { // OffLine
DB.Query("SELECT COUNT(*) FROM Scan;").then(function (result) {
var scan = DB.fetch(result);
deferred.resolve(scan);
}, function (err) {
deferred.reject(err);
});
}
return deferred.promise;
},
Save: function (scan) {
var deferred = $q.defer();
//We're OnLine
if ($rootScope.isOnLine) {
_resource.create(scan).$promise.then(function () {
scan.sync = true;
}).catch(function () {
scan.sync = false;
}).finally(function () {
DB.Insert(scan).then(function (record) {
deferred.resolve(record);
}).catch(function () {
deferred.reject();
});
});
} else { // OffLine
scan.sync = false;
DB.Insert(scan).then(function (record) {
deferred.resolve(record);
}).catch(function () {
deferred.reject();
});
}
return deferred.promise;
},
Sync: function () {
var self = this;
var deferred = $q.defer();
var allPromise = [];
//get all stored scans
self.GetNotSync().then(function (scanList) {
// send them to the server
if (scanList && scanList.length > 0)
_resourceAll.create(scanList).$promise.then(function (resp) {
//cicle on each record returned from server
resp.forEach(function (item) {
if (item) {
//prepare query
var update_query = "UPDATE Scan SET sync= 'true' WHERE idTicket= " + item.idTicket;
//set sync to true on records
allPromise.push(DB.Update(update_query));
}
});
}).catch(function (err) {
allPromise.push(deferred.reject(err));
});
}).catch(function (error) { allPromise.push(deferred.reject(error)); });
return $q.all(allPromise);
},
GetBarScan: function () {
return _resourceBar.query();
},
SaveBarScan: function (barscan) {
var deferred = $q.defer();
_resourceBar.create(barscan).$promise.then(function (record) {
deferred.resolve(record);
}).catch(function () {
deferred.reject();
});
return deferred.promise;
}
};
}
]);

angular.js - TypeError: Cannot read property 'then' of undefined

I'm trying to insert a details page of each of my captures using my service.
Though when I try loading the page with an id in my service (example: /capture/5740c1eae324ae1f19b7fc30) I get undefined, using this code:
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});
}
}
}]);
On the server side I am using mongoose/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)
Here is my server.js (extra info):
// 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);
On the client side I have the following the trigger the page:
$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();
}]);
Anyone have an idea why my find function is giving an undefined?
Help is much appreciated! Thanks
You'll need to reference underscoreJS and inject it into your service. Document: 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 _
}]);
Edit: But I'm not familiar with _.find(); if it returns a promise or not. If not, you'll need to make use of $q to create a promise and return it in order to use 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;
}
}
}
]);

Angular Node Routing

I've node on server and Angular on client...
angular routes:
var todoApp = angular.module('todoApp', ['ngResource', 'ngRoute', 'ngCookies'])
.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl: 'templates/index.html'
});
$routeProvider.when('/todo',
{
templateUrl: 'templates/todo.html',
controller:"TodoController"
});
$routeProvider.when('/admin',
{
templateUrl: 'templates/admin.html'
});
$routeProvider.otherwise({redirectTo: '/'});
$locationProvider.html5Mode(true);
});
on server side I've defined a route for '/todo'
app.use('/todo', todo);
and My todo File is
var express = require('express'),
router = express.Router(),
todo = require('../controllers/todo'),
winston = require('../../server/config/winston');
// GET users listing.
router.get('/', todo.list);
router.post('/:id', todo.save);
router.delete('/:id', todo.delete);
module.exports = router;
My Problem
if I go to home page it works fine and data shows along with loaded Pages i.e if I Enter localhost/3000/ then by default it redirects to /todo and works perfectly.
If i enter localhost/3000/todo then i only see plain text on page that is data returned from server rather then HTML page that i can see above.
I don't know whats wrong with it...
Edit
My Todo Controller
var db = require('../config/sequelize'),
StandardError = require('standard-error');
var winston = require('winston');
exports.save = function (req, res) {
if (!req.user) {
return res.send("Please Login");
}
console.log("in create", req.body);
var _task = {
task: req.body.task,
UserId: req.user.id
}
console.log(req.user);
db.Todo.create(_task).then(function (todo) {
if (!todo) {
return res.send(new StandardError('Cannot insert'));
} else {
console.log(req.body);
return res.send(todo);
}
}).catch(function (err) {
return res.send({
errors: err,
status: 500
});
});
};
exports.list = function (req, res) {
if (!req.user || req.user.isAdmin) {
return res.redirect('/');
}
console.log(db.User);
db.Todo.findAll({where: {UserId: req.user.id}}).then(function (todo) {
console.log(todo);
res.jsonp(todo);
}).catch(function (err) {
console.log(err)
res.send([{task: "No Data"}]);
});
};
exports.delete = function (req, res) {
db.Todo.destroy({
where: {
id: req.params.id,
UserId: req.user.id
}
}).then(function (response) {
console.log("deleted");
res.send(response + " Record Deleted");
//db.Todo.findAll().then(function (todo) {
// res.jsonp(todo);
// }).catch(function (err) {
// return res.render('error', {
// error: err,
// status: 500
// });
// });
});
};
May be you are confused with the angular routes and the server routes.
Use localhost/#!/todo for your todo template and localhost/todo for invoking server

what's wrong in my code that the users detail is not resolved?

Hello there i am new in express and angular and i was trying to make CRUD functionality of users.
This is my UserAjax.js file in which i have defined the get request
var router = require('express').Router()
, mongoose = require('mongoose')
, _ = require('underscore')
, Q = require('q');
module.exports = function() {
var User = mongoose.model('users');
return router
.param('/:users', function(req, res, next) {
var userId = req.params.user;
Q
.nbind(User.findById, User)(userId)
.then(function(doc) {
res.json(doc);
})
.catch(function(err){
next(err);
})
})
.get('/', function(req, res, next) {
var Query = User.find();
var qry = req.query;
Q
.nbind(Query.exec, Query)()
.then(function(docs){
res.json(docs);
})
.catch(function(err){
next(err);
});
})
.get('/:users', function(req, res, next) {
var userId = req.params.user;
var Query = user.findById(userId);
Q
.nbind(Query.exec, Query)()
.then(function(doc) {
res.json(doc);
})
.then(null, function(err) {
next(err);
})
})
.post('/', function(req, res, next){
var data = req.body;
data.createdBy = req.user._id;
Q
.nbind(User.create, User)(data)
.then(function(doc){
res.json(doc);
})
.catch(function(err){
next(err);
});
})
.put('/:users', function(req, res, next){
var userId = req.params.user;
var data = req.body;
data.lastUpdatedBy = req.user._id;
Q
.nbind(User.findById, User)(userId)
.then(function(doc){
return Q.nbind(doc.modify, doc)(data);
})
.spread(function(doc, numAffected){
res.json(doc);
})
.catch(function(err){
next(err);
});
})
.delete('/:users', function(req, res, next){
var userId = req.params.user;
Q
.nbind(User.findByIdAndUpdate, User)(userId, {
$set : {lastUpdatedBy : req.user._id, lastUpdatedOn : Date.now()}
})
.then(function(doc){
return Q.nbind(doc.remove, doc)();
})
.then(function(doc){
res.json(doc);
})
.catch(function(err){
next(err);
});
})
;
}
And this is my user state provider file where i had resolve the users detail.
'use strict';
(function() {
angular
.module('nrmcApp.user', [])
.config([
"$stateProvider"
, function($stateProvider) {
$stateProvider
.state('user', {
abstract : true
, url : "/users"
, templateUrl : '/partials/users/index'
, controller : [
"$scope"
, "$state"
, function($scope, $state) {
$scope.title = "Users";
$scope.setSelected = function(item) {
$scope.selected = item;
}
}
]
})
.state('user.list', {
url : ''
, templateUrl : '/partials/users/list'
, controller : [
"$scope"
, "$state"
, "users"
, function($scope, $state, users) {
$scope.title = "Users";
$scope.users = users || [];
$scope.setSelected = function(item) {
$scope.selected = item;
}
$scope.changeState = function() {
$state.go('user.new');
}
$scope.changeState = function() {
$state.go('user.edit');
}
$scope.changeState = function() {
$state.go('user.detail');
}
}
]
, resolve : {
"users" : ["User", function(User) {
return User.query().$promise
}]
}
})
.state('user.new', {
url : ''
, templateUrl : '/partials/users/new'
, controller : [
"$scope"
, function($scope) {
$scope.title = "Enter User Details";
}
]
})
.state('user.edit', {
url :'/edit/:userId'
, templateUrl : '/partials/users/edit'
, controller : [
"$scope"
, "users"
, function($scope, users) {
$scope.title = "Edit Users Detail"
$scope.users = users;
}
]
, resolve : {
"users" : ["User", function(User, $stateParams) {
return User.get({ id : $stateParams.user }).$promise;
}]
}
})
The problem is when i click on the link edit then it shows 404 not found.
As i mentioned the get request is not getting it .
I am totally stuck can any one help me please.
Thank You in Advance.

MEAN stack pass parameter within router

I'm a newbie to MEAN stack development. Trying to follow this tutorial https://thinkster.io/mean-stack-tutorial/ to get a simple web app working. I posted my code in the following. I created a middle layer parameter called post (see router.js file) to get a particular post. In my postCtrl, I want to pass the post/postId to the factory and get the particular post.
//$scope.post = postFactory.getById(id);
According to the tutorial, the post should be detected automatically from URL route. So I wonder how should I utilize it to get the post I want? Thanks for your time in advance
AngularController.js
var app = angular.module("littleStar" , ["service", "ui.router"]);
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: "/home.html",
controller: 'mainCtrl'
})
.state('post', {
url:'/post/{id}',
templateUrl: '/post.html',
controller:'postCtrl'
});
$urlRouterProvider.otherwise('home');
}]);
app.controller("mainCtrl", ["$scope", "$http", "postFactory", function ($scope, $http, postFactory) {
postFactory.get().success(function(data){
$scope.posts = data;
});
$scope.addPost = function() {
var title = $scope.title;
var link = $scope.link;
if (!title || title === "" || !link || link === "") {
return;
}
var newPost = {
"title": title,
"link": link
}
postFactory.create(newPost)
.success(function (data) {
postFactory.get().success(function(allPosts){
$scope.posts = allPosts;
});
});
$scope.title = "";
$scope.link = "";
};
$scope.incrementPost = function(post){
post.upvotes += 1;
};
}]);
app.controller("postCtrl", ["$scope", '$stateParams', "postFactory", function($scope, $stateParams, postFactory){
//$scope.post = postFactory.get($stateParams.id);
//$scope.post = postFactory.getById($stateParams.id);
$scope.addComment = function(){
var currentComments = postFactory.post[$stateParams.id].comments;
currentComments.push({
author:$scope.author,
body: $scope.body,
upvotes: 0
});
$scope.body = "";
}
$scope.incrementComment = function(comment){
comment.upvotes += 1;
}
}]);
router.get('/posts/:post', function(req, res) {
res.json(req.post);
});
router.param('post', function(req, res, next, id) {
var query = Post.findById(id);
query.exec(function (err, post){
if (err) { return next(err); }
if (!post) { return next(new Error('can\'t find post')); }
console(id);
req.post = post;
return next();
});
});
angularService.js
var service = angular.module("service", []);
service.factory("postFactory", ["$http", function($http){
return {
get : function(){
return $http.get("/posts");
},
create: function(newPost){
return $http.post("/post", newPost);
},
delete : function(id){
return $http.delete("/post/" + id);
},
getById : function(id){
return $http.get("posts/" + id);
}
}
}]);
You should be able to make the get post route in the following way:
router.get('/posts/:post', function(req, res) {
var query = Post.findById(req.params.post);
query.exec(function (err, post){
res.json(post);
});
});

Resources