$stateChangeError is not redirecting to home page - angular-ui-router

I am trying to redirect page to the home if user don't have access but looks like the $location.path('/') and $state.go('main') both are not working. need help to solve this issue. Any idea ?
angular.module('app').config(function($stateProvider, $urlRouterProvider, $locationProvider){
$urlRouterProvider.otherwise('/');
$stateProvider
.state('main', {
url: '/',
templateUrl: 'partials/main/main',
controller: 'fegMainCtrl'
})
.state('user-admin', {
url: '/admin/users',
templateUrl: 'partials/admin/user-list',
controller: 'fegUserListCtrl',
resolve: {
auth: function(fegIdentity, $q) {
if(fegIdentity.currentUser && fegIdentity.currentUser.roles.indexOf('admin') > -1) {
return true;
}else {
return $q.reject('not authorized');
}
}
}
});
$locationProvider.html5Mode(true);
});
angular.module('app').run(function($rootScope, $location) {
$rootScope.$on('$stateChangeError', function(event, current, previous, rejection) {
if(rejection === 'not authorized'){
$rootScope.$apply(function(){
$location.path('/');
});
}
})
});

My solution was to replace $location.path( '/state/url' ) with $state.go( 'state.name' ).
In your case (attention to the $stateChangeError parameters):
$rootScope.$on( "$stateChangeError", function( event, toState, toParams, fromState, fromParams, rejection){
if( rejection === 'not authorized' ){
return $state.go( 'main' );
}
});

Related

Laravel AJAX - How to show error in console.log

I want to show error, or to know why this code run in error:function()
Result is always run to error:function. I want to run success:function(data) and reload this page.
But console don't show anything about error.
https://imgur.com/ZubjYTc
https://imgur.com/mSfHnSR
====== Ajax ======
function ex_go(r_idx)
{
if(confirm("Are you sure?") == true)
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:'POST',
dataType: 'JSON',
url: "{{ route('change-centerYn') }}",
data:{r_idx:r_idx},
success:function(data){
alert(data.success);
location.reload();
},
error:function(xhr, data){
console.log(xhr);
},
}else{
return false;
}
}
====== Controller ======
public function ex_ok(Request $request)
{
if(request()->ajax())
{
$r_idx = 'Hello';
var_dump('<pre>', $r_idx);
return response()->json(['msg'=>'Updated Successfully', 'success'=>true]);
}
}
Since you aren't using Try & Catch or error handling your controller will return 200 HTTP header status code, which means ajax will always think that process is correct and noting went wrong, try using error handling in your controller function and raise an exception if something went wrong during your code process. you can read at this link
you can see a sample code modification to your existing code below:
public function ex_ok(Request $request)
{
try
{
if(request()->ajax())
{
$r_idx = 'Hello';
var_dump('<pre>', $r_idx);
return response()->json(['msg'=>'Updated Successfully', 'success'=>true]);
}
}
catch(\Exception $e)
{
\Log::error($e); // create a log for error occurrence at storage/log/laravel.log file
return response()->json($e->getData(), $e->getStatusCode());
}
}
It's suddenly working! Unbelievable!
Thank you very much! You saved my morning!
Use try catch
========= AJAX ===========
function ex_go(r_idx)
{
if(confirm("해당 결제건을 지원센터로 보내시겠습니까?") == true)
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
console.log(r_idx);
$.ajax({
type:'POST',
dataType: 'JSON',
url: "{{ route('change-centerYn') }}",
data:{r_idx:r_idx},
success:function(data){
alert(data.success);
location.reload();
},
error:function(xhr, data){
console.log(xhr);
}
});
}else{
return false;
}
}
========= Laravel Controller =======
public function ex_ok(Request $request)
{
try
{
if(request()->ajax())
{
$r_idx = $request->r_idx;
$lecture = DB::table('class_order')
->select('*')
->where('r_idx', '=', $r_idx)
->first();
if ($lecture->r_oid != '') {
$insert_data = [
'r_oid' => $lecture->r_oid,
'r_user_id' => $lecture->r_user_id,
'r_name' => $lecture->r_name,
'r_tel' => $lecture->r_tel,
'r_hp' => $lecture->r_hp,
'r_email' => $lecture->r_email,
'r_zip' => $lecture->r_zip,
'r_addr1' => $lecture->r_addr1,
'r_addr2' => $lecture->r_addr2,
'r_class' => $lecture->r_class,
'r_enddate' => $lecture->r_enddate,
'app_endday' => $lecture->app_endday,
'whole_study' => $lecture->whole_study,
];
DB::table('ex_class_order')->insert($insert_data);
ClassOrder::where('r_idx', '=', $r_idx)->update(['centerYn' => 'y']);
$info_txt = "처리되었습니다.";
}
else
{
$info_txt = "처리실패";
}
return response()->json(['msg'=>'Updated Successfully', 'success'=>true]);
}
}
catch(\Exception $e)
{
\Log::error($e); // create a log for error occurrence at storage/log/laravel.log file
return response()->json($e->getData(), $e->getStatusCode());
}
}

Redirect to home page after submit form vue

i have created login with rest-full api login system with vue 2 laravel
i want after login it should redirect to another page like /
i have tried with add then redirect: '/'
here is my script
<script>
export default {
data(){
return{
loginDetails:{
email:'',
password:'',
remember:true
},
errorsEmail: false,
errorsPassword: false,
emailError:null,
passwordError:null
}
},
methods:{
loginPost(){
let vm = this;
axios.post('/login', vm.loginDetails)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
var errors = error.response
if(errors.statusText === 'Unprocessable Entity'){
if(errors.data){
if(errors.data.email){
vm.errorsEmail = true
vm.emailError = _.isArray(errors.data.email) ? errors.data.email[0]: errors.data.email
}
if(errors.data.password){
vm.errorsPassword = true
vm.passwordError = _.isArray(errors.data.password) ? errors.data.password[0] : errors.data.password
}
}
}
});
}
},
mounted() {
}
}
this may help
loginPost(){
axios.post('/login', this.loginDetails)
.then(function (response) {
if(response.status === 200) {
this.$router.push({ path : '/' });
}
})
}

React Displaying List of Items from Ajax request

I am learning React and I am trying to display a list of users from and ajax call. I am getting an unexpected token error from CodePen when I add the line
export default Users;
When I remove the line there are no more errors but the list of users is not being displayed.
My code:
function GetUsers(project){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function (data) {
console.log(data);
callback(null, data);
},
error: function (error) {
console.log(data);
callback(error, {});
}
});
}
function UserList(users) {
const userItems = users.map((user) =>
<ul>
<li>
{ user.name }
</li>
<li>
{ user.email }
</li>
<li>
{ user.phone}
</li>
</ul>
);
return (userItems);
}
class Users extends Component {
componentDidMount() {
GetUsers(null, function (err, data) {
if (err)
{
console.log(err);
}// do something
this.setState({ users: data })
}.bind(this))
}
render() {
return(
<UserList user = {this.state.users} />
);
}
}
if (document.getElementById('root')) {
ReactDOM.render(<Users />, document.getElementById('root'));
}
Here is my code.
Thank you for any and all help!
Problem 1 in AJAX call
function GetUsers(project){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function (data) {
console.log(data);
callback(null, data);
},
error: function (error) {
console.log(data);
callback(error, {});
}
});
}
$.ajax is asynchronous call, that means it doesn't returns directly any value (how it could if it is fetching the results from the internet) it Just creates another function which will call success and error when completed.
That's why we need to wrap it with callbacks
function GetUsers(project, resolve = () => {}, reject = () => {}) {
}
Problem 2 in mount
componentDidMount() {
GetUsers(null, function (err, data) {
if (err)
{
console.log(err);
}// do something
this.setState({ users: data })
}.bind(this))
}
This code is completely wrong, it has even syntax error so not worth to discuss it in details.
We need to call our new function and pass success callback for mutating the state
GetUsers(null, users => {
this.setState({ users });
});
In this way we will call GetUsers wait for it's results and only after that we will mutate the state with new result
3 problem in component creation
React component's don't have state by default, you need to infer the state from constructor so we need to change initialization to
constructor(props) {
super(props);
this.state = {
users: false
};
}
otherwise you will get Cannot call setState of undefined as state is not automatically created for performance purposes and all components are Pure by default.
I have created a working sandbox here
in
function GetUsers(project){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function (data) {
return data;
},
error: function (error) {
console.log(error);
return {};
}
});
}
--
success: function (data) {
return data;
}
doesn't do what you think it does. return data isn't really returning the data... anywhere.
You need to have a callback.
function GetUsers(project, callback){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function (data) {
callback(null, data)
},
error: function (error) {
callback(error, {})
}
});
}
class Users extends Component {
componentDidMount() {
GetUsers(null, function (err, data) {
if (err) // do something
this.setState({ users: data })
}.bind(this))
}
render() {
return(
<UserList user = {this.state.users} />
);
}
}
you can also Promise-ify things to simplify the logic

Does Vue.JS work with AJAX http calls?

I am trying to do the following from my HTML:
var vm = new Vue({
el: '#loginContent',
data: {
main_message: 'Login',
isLoggedIn: false,
loginError: '',
loginButton:'Login'
},
methods: {
onLogin: function() {
//this.$set(loginSubmit, 'Logging In...');
var data = {
email: $('#email').val(),
password: $('#password').val(),
};
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then(function (response) {
if(response.error) {
console.err("There was an error " + response.error);
this.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
this.isLoggedIn = true;
} else {
this.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
}
}
});
Basically user presses the login button, onLogin method is called that sends a post to my API. The post is working fine and I do get the response back in the .then() promise.
But, trying to do things like this.isLoggedIn = true; does not update my DOM with what I am expecting the HTML to do when the user logs in.
Could be that I am in some sort of background thread (sorry, mobile developer here) when I get the response in the promise and it can't find the "vm" instance?
Thanks
It is probably happening because your this is not pointing to correct scope, scope of this changes inside an $.ajax call, so you just have to do something like following:
methods: {
onLogin: function() {
//this.$set(loginSubmit, 'Logging In...');
var data = {
email: $('#email').val(),
password: $('#password').val(),
};
var that = this
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then(function (response) {
if(response.error) {
console.err("There was an error " + response.error);
that.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
that.isLoggedIn = true;
} else {
that.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
}
}
I would propose another method use ES6 Arrow Functions like '=>'. It is simple and do not need extra variable.Like following:
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then((response) => {
if(response.error) {
console.err("There was an error " + response.error);
this.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
this.isLoggedIn = true;
} else {
this.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
You might want to take a look at axios. I used $.ajax and got it working, but found axios and prefer axios over the ajax library.

testing ui-router stateprovider 'resolve:' values

I'm using jasmine+karma to run the following code...
and get the following error:
Expected { then : Function, catch : Function, finally : Function } to equal 123.
Can someone help me understand why I don't get a resolved value for my promise. thanks
'use strict';
angular
.module('example', ['ui.router'])
.config(function($stateProvider) {
$stateProvider
.state('stateOne', {
url: '/stateOne',
resolve: {cb: function($q) {
var deferred = $q.defer();
deferred.resolve(123);
return deferred.promise;
}},
controller: function($scope, cb) {console.log(' * in controller', cb);},
templateUrl: 'stateOne.html'
});
})
.run(function($templateCache) {
$templateCache.put('stateOne.html', 'This is the content of the template');
});
describe('main tests', function() {
beforeEach(function() {module('example');});
describe('basic test', function($rootScope) {
it('stateOne', inject(function($rootScope, $state, $injector, $compile) {
var config = $state.get('stateOne');
expect(config.url).toEqual('/stateOne');
$compile('<div ui-view/>')($rootScope);
$rootScope.$digest();
expect($injector.invoke(config.resolve.cb)).toEqual(123);
}));
});
});
Ok, Figured it out with some help (via email) from Nikas, whose blog I found at:
http://nikas.praninskas.com/angular/2014/09/27/unit-testing-ui-router-configuration/.
Here is a succinct example that demonstrates how to test the resolve values in ui.router, where the values involve $http.
angular
.module('example', ['ui.router'])
.factory('Clipboard', function($http) {
return {
get: function(args) {
return $http.get('/db/clipboard');
}
};
})
.config(function($stateProvider) {
$stateProvider
.state('stateOne', {
resolve: {cb: function(Clipboard) {
return Clipboard.get();
}}
});
});
describe('main tests', function() {
beforeEach(function() {module('example');});
it('stateOne', inject(function($state, $injector, $httpBackend) {
$httpBackend.whenGET('/db/clipboard').respond({a:1});
$injector.invoke($state.get('stateOne').resolve['cb'])
.then(function(res) {console.log(' *res ', res.data);})
.catch(function(err) {console.log(' *err ', err);});
$httpBackend.flush();
}));
afterEach(inject(function($httpBackend) {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
}));
});

Resources