nodeJS and AngularjS -app.get method was never been called - angularjs

I really dont know what I am doing wrong ...but my app.get function doesn t work ..when I try to look at networking in Chrome ..there was a HTTP status 302 Found ..but its never go into that function on server side ..I really dont know what I am doing wrong ..help please. .or ask more information I dont know what should be the important ..
Here is my server.js function :
app.get('/api/tests/:id', function(req, res, next) {
console.log('get tests id')
console.log(req.params.id)
Test.findById(req.params.id, function(err, test) {
if (err) return next(err);
console.log(test)
res.send(test);
});
});
here is app.js Angular rouiting ..
.when('/tests/:id',{
templateUrl: 'templates/testView.html',
controller: 'TestViewCtrl'
})
.otherwise({
redirectTo: '/'
});
here is my HTML menu.html file ..where I want to go on that specific address:
<div ng-repeat="test in tests">
<div>
{{test.testName}}
</div>
</div>
..in controller menu.html I´ve got post method because GET method too doesnt work ..
$scope.getTests = function () {
$http.post('/api/getTestText')
.success(function (data) {
$scope.tests = data;
and in detail page for each test is my HTML till now blank ..but in Controller I have something like this :
.controller('TestViewCtrl', ['$scope', '$http','$routeParams','Test', function ($scope, $http, $routeParams, Test) {
Test.get({_id: $routeParams.id},function(test){
$scope.test=test;
console.log($scope.test)
and test factory.js :
.factory('Test', ['$resource', function ($resource) {
return $resource('/api/tests/:id');
}]);
I dont think so that the problem is in front-End side ..but maybe is ..
I heard something about postman app from google chrome apps ...but when I type there my HTTP call ..
localhost:3000/api/tests/ and as params I set _id and IDvalue as value ..the result is same like when I do it by click on menu Item ..
localhost:3000/api/tests?id=5726aa164a26bbe4180700ea
But console.log no working in the server.js side ..so it never goes into app.get() I think...

You need to map the _id field from the body into :id in the url param.
To achieve this, change this:
.factory('Test', ['$resource', function ($resource) {
return $resource('/api/tests/:id');
}]);
Into:
.factory('Test', ['$resource', function ($resource) {
//This plugs in the _id field from the body and injects it into the url param.
//This is an example with mongodb default _id field assuming that's what you use.
return $resource('/api/tests/:id', {id: '#_id'});
}]);

Related

Controller is not getting call when its state is changing

I am using ui-router for routing my angular app. I have set the routing configuration but didn't want to use controller as syntax. I am using following syntax:
.state('blog',{
url: '/blog',
templateUrl: '/templates/blog.html',
controller: 'BlogController'
})
However the template is being called into my ui-view but I BlogController is not being called. I have used console.log() into my BlogController but I didn't see anything in my console. Here is my BlogController.js
app.controller('BlogController', function($scope, PostService,){
console.log(0);
PostService.getPost().then(function(post){
$scope.postModel = post;
});
console.log(1);
});
As you can see, I am using a service to call data using $http. Below is my PostService :
app.service('PostService', function ($http) {
this.getPost = function () {
return $http({
method : 'GET',
url : 'http://domain.com/wp-json/wp/v2/posts'
})
.then(function(response){
return response.data;
}, function(error){
return error;
});
};
});
I think this the problem related to the service call. I have read some post about resolve property in state method of ui-router. I have tried that but nothing has working. Can somebody please help me to get rid out of this ?
The declaration of the ui-router module is wrong
var app = angular.module('mySiteApp', [require('angular-ui-router')])
Should be,
var app = angular.module('mySiteApp', ['ui.router'])
Check this link for cors errors

How can I handle email confirmation URLs in an Identity 2.1 SPA Angular JS Application?

I have seen an example that uses MVC. It has a return URL which comes up with a screen that is called from the email sent out. But I have an SPA AngularJS application so it is a bit different. Has anyone tried to do this with a SPA and if so how did they go about implementing it. Any pointers would be much appreciated.
I'm working on the same now; needs more work to make it pretty and whatnot, but hopefully you get the general idea.
The confirmation URL looks like:
http://localhost:8000/app.html#/confirm/9a28aa89e84e80153b1f2083d38911acbae12e8365dd13c83cee55f79481e1f8
(localhost:8000 because I'm testing). I then have a route for ui-router:
var confirm = {
name: 'confirm',
url: '/confirm/:auth',
templateUrl: 'app/front/partial/confirm.html',
params: {auth: {}}
} ;
$stateProvider.state(confirm) ;
the confirm.html partial (which obviously needs fleshing out a bit!) is:
<div ng-controller="Fapi.Front.Confirm.Ctrl">
CONFIRM
</div>
and the controller is:
angular.module('myApp')
.controller('App.Front.Confirm.Ctrl', [
'$scope', '$state', '$stateParams', 'toaster', 'MyDataService',
function ($scope, $state, $stateParams, toaster, MyDataService) {
MyDataService.confirm (
{auth: $stateParams.auth},
function (data) {
toaster.pop('success', 'Your registration has been confirmed') ;
setTimeout(function () { $state.go('login') }, 5000) ;
},
function (data) {
toaster.pop('error', data.message) ;
}
)
}]) ;
MyDataService is just a service that wraps $http calls to the server.
So, instead of the 'usual' situation where the URL invokes a script on the server which does the work, and then renders a 'you have been confirmed' (or not) page, here the router takes the browser to a page that then makes an AJAX call to the server to do the confirmation.

Restrict access to route with routeprovider unless variable as been set

I'm in the process of learning AngularJS, working on a more in-depth ToDo app. I'm having an issue with trying to limit access to a url or "route" using angular.
When you hit my dev url on my machine (todo.ang) it brings you to todo.ang/#/home, on this view you see the categories which have todos associated to each. EG (category = cat, cat has a todo of "feed", and "play"), when you click a category I'm calling the $scope.goToCategory function (seen in my JS fiddle) which sets a variable for my firebase ref then redirects you too /#/todo. This is working correctly.
My problem is, I don't want the user to be able to access /#/todo if the todoRef variable is still undefined. But it seems like even after $scope.goToCategory is called and todoRef is set to a firebase URL, the routerprovider never gets recalled to know that todoRef has been set to a different value so it always forces you back to /#/home.
code:
var todoRef = undefined;
if (todoRef !== undefined) {
$routeProvider.when('/todo', {
templateUrl: 'views/todo.html',
controller: 'TodoCtrl'
});
}
$scope.goToCategory = function(catId) {
test = catId;
todoRef = new Firebase("URL HERE");
$location.path('/todo');
}
I didn't include the entire file of code but if thats necessary, I can do that as well.
JSFiddle
All routes are only being set during the config phase.
what happens in your code is that 'todo' route is ignored during the initiation of ngRoute.
What you should do is to setup the route but have a resolve like so:
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/todo', {
templateUrl: 'views/todo.html',
controller: 'TodoCtrl',
resolve: {
todoRef: ['$q', function($q) {
return todoRef ? todoRef : $q.reject('no ref');
}]
}
});
}]);
If 'todoRef' is undefined the route is rejected.
Also you should consider moving 'todoRef' into a service and not on global scope.
You can also listen for route errors and for example redirect to home route:
app.run(['$rootScope', '$location', function($rootScope, $location) {
$rootScope.$on('$routeChangeError', function() {
$location.path('/home');
});
}]);

Refused to execute script from '*' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled

I am a newbie to AngularJS. I am using a rails application to expose data in json format. The data is to be used by angular app. The angular repo and the rails repo are completely different. The reason for different repositories is because I want my rails repo just to expose data using APIs which i can use in the angular app.
My rails controller is as below
class Api::V1::PhonesController < ApplicationController
def index
render json: Phone.all
end
def show
render json: Phone.find(params[:id])
end
...
end
Now, when i visit 'localhost:3000/api/v1/phones', it returns me the json data for all the phones. When I visit 'localhost:3000/api/v1/phones/1', it returns the the json data for the phone with id 1. I validated the json data format using http://jsonlint.com/. Everything works fine till here.
My angularjs route file is as:
$routeProvider.
when('/phones', {
templateUrl: 'list.html',
controller: 'PhoneListController'
}).
when('/phones/:id', {
templateUrl: 'show.html',
controller: 'PhoneShowController'
}).
otherwise({
redirectTo: '/phones'
});
}]);
My index.html in the angular repo has the list.html template embedded in it.
<html ng-app='phoneCatApp'>
...
</html>
<script type="text/ng-template" id="list.html">
This is the list template.
</script>
the code for the services.js is as:
var appServices = angular.module('appServices', []);
phoneCatApp.factory('appServices', ['$http', '$q', function($http, $q){
var url = "http://localhost:3000/api/v1/";
//get all phones
this.getPhones = function(){
var defered = $q.defer();
var listApi = url + "phones";
$http.jsonp(listApi).then(function(results){
defered.resolve(results);
}, function(error){
defered.reject(error);
});
return defered.promise;
}
return this;
}]);
The text in the script template is displayed as well when I visit '#/phones'. The problem is that
1) In chrome, following error is displayed when i inspect the page.
Refused to execute script from 'http://localhost:3000/api/v1/phones' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.
2) in firefox, the following error is getting displayed.
SyntaxError: missing ; before statement
Thanks for the help.
Hey so I believe your problem is that your rails controller is returning JSON and NOT JSONP. Your controller has to explicitly specify a callback function, which can be specified by the request params.
See Handling jsonp in rails 3 controller for an example of returning JSONP from a rails controller
So your rails code would look like (argh my rails is very very rusty...):
class Api::V1::PhonesController < ApplicationController
def index
if params[:callback]
format.js { render :json => {:phones => Phone.all.to_json}, :callback => params[:callback] }
else
format.json { render json: {:phones => Phone.all.to_json}}
end
end
Then for the angular side, this answer should help you out:
parsing JSONP $http.jsonp() response in angular.js
And I think your angular would then look like:
var appServices = angular.module('appServices', []);
phoneCatApp.factory('appServices', ['$http', '$q', function($http, $q){
var url = "http://localhost:3000/api/v1/";
//get all phones
this.getPhones = function(){
var defered = $q.defer();
var listApi = url + "phones?callback=JSON_CALLBACK";
$http.jsonp(listApi).then(function(results){
defered.resolve(results);
}, function(error){
defered.reject(error);
});
return defered.promise;
}
return this;
}]);

Templates from templatecache not rendering bindings when data is returned from $http in 1.2+

I have a basic app, that fetches some data through the $http service, however it doesnt render the data correct in the template, when the template is served from the template cache. My code looks like this:
angular.module('app', [])
api service:
.factory('api', function($http, $q) {
return {
getCars: function() {
return $http.get('api/cars');
}
};
})
the controller using the service:
.controller('carsCtrl', function($scope, api) {
api.getCars().success(function(data) {
$scope.cars = data;
});
})
the route setup:
.config(function($routeProvider) {
$routeProvider.when('/cars', {
templateUrl: 'cars.html',
controller: 'carsCtrl'
});
});
and the template cars.html
<div ng-repeat="car in cars">
{{ car }}
</div>
this works the first time the browser hits /cars, however, if I push the back on forward button in the browser to hit the url a second time without a page reload, the {{car}} is not being rendered. If the cars.html is put in the templateCache like this:
angular.module('app').run(function($templateCache) {
$templateCache.put('cars.html', '<div ng-repeat="car in cars">{{ car }}</div>');
});
the {{car}} binding is not rendered either.
I suspect this has something to do with Angular not unwrapping promises in templates anymore, but not totally sure. Does anyone know what I am doing wrong and how to write this code correctly?
Well, I saw some syntax errors in your code (maybe you didn't copy the code but typed it manually for SO not sure). Also you returned deferred instead of deferred.promise. What you trying to achieve works just fine:
Plnkr Example

Resources