Displaying data from MongoDB (MEAN Stack) - javascript

I am trying to displaying some data from a Mongo DB onto the front-end. I am working with the MEAN stack, which I'm relatively new at.
I have successfully gotten the data to display in JSON format at a localhost URL (localhost:3030/incidents), but cannot get the clean data to appear on the front end (which is at localhost:9000).
This is what my code looks like so far for the server side (router.js):
"use strict";
var config = require('../config/database-config');
var Router = function (options) {
var self = this;
self.environment = options.environment;
self.route = function(app) {
var IncidentController = require('./controllers/incident-controller.js');
var IncidentModel = require('./models/incident-model.js');
var incidentModel = new IncidentModel(config[`${self.environment}`]);
console.log("Incident Model", incidentModel);
var incidentController = new IncidentController({model: incidentModel});
app.get('/api/incident/:id', incidentController.findIncidentById);
app.get('/incidents', incidentController.getAllIncidents);
};
return self;
};
module.exports = Router;
Client side:
services.js:
'use strict';
angular.module('victimList.services', []).factory('Victim', function($resource) {
return $resource('http://localhost:3030/api/incident/:id');
});
data.js:
'use strict';
angular.module('victimList', [])
.service('victimList')
.controller('DataCtrl', ['victimService', function ($scope, victimService) {
victimService.getVictims(function(victims) {
$scope.victims = victims;
});
}])
.factory('victimSerivce', function($http) {
var getVictims = function(callback) {
$http.get('http://localhost:3030/incidents').success(function(data){
callback(data);
});
};
return {
getVictims: getVictims
};
});
app.js:
'use strict';
angular
.module('frontendApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'victimList',
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.when('/victims', {
templateUrl: 'views/victims.html',
controller: 'DataCtrl',
controllerAs: 'victims'
})
.otherwise({
redirectTo: '/'
});
});
victims.html:
<div ng-app="victimList">
<h1>Testing</h1>
<div ng-controller="DataCtrl">
<ul ng-repeat="victim in victims">
<li>1</li>
<li>{{ victim.firstname }} {{ victim.lastname }}</li>
</ul>
</div>
When I navigate to the localhost:9000/victims page, I get the header tag, but no data. The console shows this error:
Error: [$injector:unpr] Unknown provider: victimServiceProvider <- victimService <- DataCtrl
What could I be missing? Thanks in advance for your help!

I figured it out! I needed to add the following:
angular.module('victimList', [])
.service('victimService')
.controller('DataCtrl', ['$scope', 'victimService', function ($scope, victimService) {
victimService.getVictims(function(victims) {
$scope.victims = victims;
});
}])
^^ Note that '$scope' was added on line 3.

Related

Destroying AngularJS $Http.Get Cache

I can't figure out how to destroy my cache to get a new list from my server.
When I get the first list, it's work perfect, but after inserting informations to my database and sending another get to my server, the browser only show the cached version of my list, without the new data.
I tried to use cacheFactory like this:
$cacheFactory.get('$http').removeAll();
but it doesn't worked.
Here is my angular Module, Service and Controller.
Module myApp
var app = angular.module('myApp', ['ngRoute', 'LocalStorageModule', 'angular-loading-bar', 'smart-table']);
app.config(function ($routeProvider) {
$routeProvider.when("/home", {
controller: "homeController",
templateUrl: "/web/views/home.html"
});
$routeProvider.when("/cidades", {
controller: "cidadesController",
templateUrl: "/web/views/basico/cidades/cidades.html"
});
$routeProvider.otherwise({ redirectTo: "/home" });
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptorService');
});
app.run(['authService', function (authService) {
authService.fillAuthData();
}]);
cidadesService
'use strict';
app.factory('cidadesService', ['$http', '$cacheFactory', function ($http, $cacheFactory) {
var serviceBase = 'http://localhost:22207/';
var serviceFactory = {};
var _getCidades = function () {
$cacheFactory.get('$http').removeAll(); //This doesn't worked
return $http.get(serviceBase + 'api/cidades/getall').then(function (results) {
return results;
});
};
serviceFactory.getCidades = _getCidades;
return serviceFactory;
}]);
cidadesController
'use strict';
app.controller('cidadesController', ['$scope', 'cidadesService', function ($scope, service) {
$scope.cidade = {
id: "",
nome:"",
};
$scope.message = "";
$scope.getCidades = function () {
service.getCidades().then(function (results) {
$scope.cidades = [];
$scope.collection = [];
$scope.cidades = results.data;
$scope.collection = [].concat($scope.cidades);
}, function (err) {
$scope.message = err.error_description;
});
};
//Initializing the list
$scope.getCidades();
}]);
I really don't see anything wrong, but in any case you can add unique param for your request to prevent caching
like
$http.get(serviceBase + 'api/cidades/getall?unique=' + new Date().getTime())

angular unknown provider error using factory and ui.router resolve

I'm getting unknown provider error when i'm trying to use resolve from a state. The object i want returned seems to be returned correctly, so i can't really figure out what the problem is.
This is my first angular project so if I something seems wierd it probably is.
The error: https://docs.angularjs.org/error/$injector/unpr?p0=boardProvider%20%3C-%20board%20%3C-%20AppCtrl
var ponk = angular.module("ponk", ["ui.router", "ngResource"]);
ponk.config(['$stateProvider', '$urlRouterProvider',
"$locationProvider", function ($stateProvider, $urlRouterProvider,
$locationProvider) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
$stateProvider.state('board', {
url: '/b/:slug',
templateUrl: 'views/board.html',
controller: "AppCtrl",
controllerAs: "pk",
resolve: {
board: function($stateParams, boardFactory) {
var board = {};
if($stateParams.slug) {
board = boardFactory.get({slug:$stateParams.slug}).$promise;
}
return board;
}
}
});
}]).run(function($state) { $state.go('board'); });;
ponk.factory("boardFactory", ["$http", "$resource",
function($http, $resource) {
return $resource('/board/:slug', {slug:'slug'}, {update: { method: "PUT" }});
}]);
ponk.controller("AppCtrl", ["$scope", "$http", "boardFactory", "board",
function($scope, $http, boardFactory, board ) {
console.log(board); // correct object, but error
}]);
EDIT:
discovered the above code works. The problem is when i add this to the controller:
var pk = this;
var pk.board = board;

unable to pass data between the views in angularjs through routing

In my angularjs app, I am trying to pass the data from one cshtml view to another view through routing but in details.cshtml, I don't see the data coming into it though I can see the change in URL
Index.cshtml (View1)
{{addprodtocart}}
Controller.js
app.controller('CartController', function ($scope) {
$scope.SendToCartPage = function(cartprd)
{
var len = cartprd.length - 1;
$scope.cid = cartprd[len];
}
});
Details.cshtml ( I don't see the data coming into the span below)
<div ng-controller="CartController">
<span ng-model="cid">{{cid}}</span>
</div>
Myrouting
var app = angular.module("productmodule", ["ngRoute"]);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/Details/:cid', {
templateUrl: '/Product/Details',
controller: 'CartController'
});
}]);
I created a plunker for this. I am unable to send the data from page1 to page2
http://plnkr.co/edit/micM7vlslznEIZXP293Y?p=preview
Your problem is your controller is instantiated again while clicking on href and the scope is getting recreated & $scope.cid is set to undefined.
You could achieve the same by using $routeParams which will give the access to what url contains
In your case it would be $routeParams.cid
Code
app.controller('CartController', function ($scope, $routeParams) {
$scope.SendToCartPage = function(cartprd)
{
var len = cartprd.length - 1;
//$scope.cid = cartprd[len];
}
$scope.cid = $routeParams.cid;
});
Update
You should use $routeParams service to get data from url
Code
var app = angular.module('plunker', ['ngRoute']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/Details/:cid', {
templateUrl: 'page2.html',
controller: 'CartController'
}).when('/', {
templateUrl: 'page1.html',
controller: 'CartController'
});
}
]);
app.controller('CartController', function($scope, $routeParams) {
$scope.myvar = $routeParams.cid; //this will asign value if `$routeParams` has value
console.log($scope.myvar);
$scope.Add = function(c) {
$scope.myvar = c;
}
});
Working Plunkr

Angularjs Restful using ngResource not working

I am trying to expose restful web service using angularjs ngResource using java as my backend everything seems to be correct but don't know What is wrong with my code
nothing gets displayed in browser help me with this
service.js
'use strict';
var employeeServices = angular.module('myApp.services',['ngResource']);
employeeServices.factory('Employees',['$resource',function ($resource){
return $resource('my service link', {},{
query:{method:'GET',isArray:true}
});
}]);
Controller.js
'use strict';
angular.module('myApp.controllers',[]).
controller('Myctrl1',['$scope','Employees',function ($scope ,Employees){
$scope.allemployees = Employees.query();
}]).
controller('Myctrl2',[function (){
}]);
app.js
'use strict';
angular.module("myApp", [
'ngRoute',
'myApp.controllers',
'myApp.services'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1',{templateUrl:'partials/partials.html',controller:'Myctrl1'});
$routeProvider.when('/view2',{templateUrl:'partials/partials1.html',controller:'Myctrl2'});
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
If you want to use service of one module in another module you have to inject it.
service.js
'use strict';
var employeeServices = angular.module('myApp.services', ['ngResource']);
employeeServices.factory('Employees', ['$resource', function ($resource) {
return $resource('my service link', {}, {
query: { method: 'GET', isArray: true }
});
}]);
Controller.js
'use strict';
angular.module('myApp.controllers', ['myApp.services']).
controller('Myctrl1', ['$scope', 'Employees', function ($scope, Employees) {
$scope.allemployees = Employees.query();
}]).
controller('Myctrl2', [function () {
}]);
app.js
'use strict';`enter code here`
angular.module("myApp", [
'ngRoute',
'myApp.controllers',
'myApp.services'
]).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/view1', { templateUrl: 'partials/partials.html', controller: 'Myctrl1' });
$routeProvider.when('/view2', { templateUrl: 'partials/partials1.html', controller: 'Myctrl2' });
$routeProvider.otherwise({ redirectTo: '/view1' });
}]);
try this

Error: Unknown provider: SessionProvider <- Session AngularJS

I am aware that the error which is in the title of this question is basically because in my controller I am injecting a Session service in my controller that has not been defined. I am currently looking at: Angular Devise for which I am rolling out in an application that is using rails but have angular and rails separate. My setup on the angular side is as followed:
main.js
angular.module('App.controllers', []);
angular.module('App.config', []);
angular.module('App.directives', [])
angular.module('App.resources', ['ngResource']);
angular.module('App.services', []);
var App = angular.module("App", [
"ngResource",
"ngCookies",
"$strap.directives",
"App.services",
"App.directives",
"App.resources",
"App.controllers",
"TotemApp.config"
], function ($routeProvider, $locationProvider, $httpProvider) {
var interceptor = ['$rootScope', '$q', function (scope, $q) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 401) {
window.location = "/login";
return;
}
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
});
Session.js
App.service('Session',[ '$cookieStore', 'UserSession', 'UserRegistration', function($cookieStore, UserSession, UserRegistration) {
this.currentUser = function() {
return $cookieStore.get('_angular_devise_user');
}
this.signedIn = function() {
return !!this.currentUser();
}
this.signedOut = function() {
return !this.signedIn();
}
this.userSession = new UserSession( { email:"sample#email.com", password:"password", remember_me:true } );
this.userRegistration = new UserRegistration( { email:"sample#email.com", password:"password", password_confirmation:"password" } );
}]);
sessions_controller
App.controller('SessionsController', ['$scope', '$location', '$cookieStore', 'Session', function($scope, $location, $cookieStore, Session) {
$scope.session = Session.userSession;
$scope.create = function() {
if ( Session.signedOut ) {
$scope.session.$save().success(function(data, status, headers, config) {
$cookieStore.put('_angular_devise_user', Session.userSession.email);
$location.path('/todos');
});
}
};
$scope.destroy = function() {
$cookieStore.remove('_angular_devise_user');
$scope.session.$destroy();
};
}]);
routes.js
'use strict';
App.config(function($routeProvider, $httpProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main/home.html',
controller: 'MainCtrl'
})
.when('/login', {
templateUrl: 'views/sessions/new.html',
controller: 'SessionsController'
})
.when('/sign_up', {
templateUrl: 'views/registrations/new.html',
controller: 'RegistrationsController'
})
.otherwise({
redirectTo: '/'
});
});
This error occurs when I try to access the login page or register page. If someone can shed some light that would be greatly appreciated. Not entirely sure how to resolve this Error: Unknown provider: $SessionProvider <- $Session error
At first glance this looks correct. I can only assume that perhaps you've not included Session.js in your index.html file?
Angular clearly doesn't know what 'Session' service is so there's something wrong there either file not loaded, not loaded correctly or something along those lines as far as I can see.
Edit: Does the error say 'SessionProvider <- Session' or '$SessionProvider -< $session' because if it's the latter, then something is named wrong somewhere in your app since your service is named 'Session' not '$Session'.
When you have syntax error in other javascript or typescript files. You will get the same error. Please make sure that you have no syntax error.

Categories

Resources