Comparing $location.path() to route with params not working - angularjs

I have an app where I must allow non logged in users to access some pages, such as forget password form, registration etc.
if(!Authentication.isLoggedIn()){
if($location.path() === '/thanks'){
// Allow
} else {
// Redirect to login
$location.path('/login');
}
}
I am using ngRoute and I have a route with a param in it (/lostpassword/:token) but I can't find a way to compare it properly to allow it the same way I can for /thanks
So to clarify, I am not looking for the value of :token, I just want to be able to tell when the route /lostpassword/:token is being viewed.
I am really new to angular and I'm hoping it is just a small syntax issue. Any help would be appreciated.

In case you want to know if the url contains a keyword you can do:
var path = $location.path();
if (path.split('/').indexOf('some') > -1){
// do something
}
Angular $location docs
EDIT
You can also use angular router which can get a url template. this is the preferred way to handle routes within you application.

Related

Restrict access to a page in Gatsby.js to logged in users

On my gatsby.js static site, I want to restrict access to my pages/dashboard page using client-side authentication. The plug-in, gatsby-plugin-meta-redirect says that I can create a redirect with this...
createRedirect({ fromPath: '/old-url', toPath: '/new-url', isPermanent: true });
...but I'm not sure where to place that in my code. I'm assuming gatsby-node.js, but I'm not sure how.
I want to do something like this,
if (user.loggedIn) {
// redirect to '/dashboard'
} else {
// redirect to '/'
}
This is assuming that the state of user is available throughout the site. Is this possible?
Also, in the gatsby-plugin-meta-redirect docs, it states that this plugin should be put last in the array in gatsby-config.js. But I already have gatsby-plugin-netlify placed last. Would that be a problem?
What you can do is give a programmatic, non-direct access to the /dashboard page using navigateTo in Link.
See this issue.

Dynamic parameters with ui-router

I'm developing a search app with angular using ui-router.
Requirements:
The search form has too many fields and all have to be optional.
Users should share with another users the URL that display the page with the result list. (So I need to use querystring)
So I could have urls like
path/to/url/list?p=123&v=876
path/to/url/list?c=yes&a=true&p=123
path/to/url/list?z=yes&c=yes&a=true&p=123
path/to/url/list?z=yes&v=876&a=true&p=123
And endless combinations. I know that I can use $location.search() to get all params in json format. That is great! but the question is How can I define the url state with ui-router? Define explicitly all params in the url is not an option. I have read many post but I didn't find a concrete answers.
If you're getting parameters from $location you don't need to define them in state explicitly.
I think, the best way is to use 'resolve' property of $stateProvider configuration:
$stateProvider.state('mystate', {
// Some code here
resolve: {
queryData: ['$location', ($location) => {
$location.absUrl(); // Contains your full URI
return true;
}]
}
});
It's kind of initialization. After that, ui-router will cut URI, but you will store needed data. This case also works fine, when user passing URI directly in browser address input.
Also you can try to set $urlRouterProvider with $urlMatcher for this purposes, but it will be more difficult.

Hash removed from default routing in AngularJS

I'm writing an angular app where I need to accept an URL with a fragment hash (OAuth 2.0). Making it short it looks like this.
http://example.com/#access_token=918f4d6e90b25b13ef66a
When this URI is loaded, the routing process does not recognize the path and and it correctly redirects the app to the default route. The problem is that in thi way I loose the hash and I can't parse it anymore.
What I want to do is to parse the hash before it gets removed.
Do you have any idea on a possible solution?
Thanks.
P.S. In this app I can't use HTML5 mode. With it enabled it works just fine.
You just need to define an extra route to "catch" and save the access-token, before redirecting to another route.
E.g.:
$routeProvider
...
.when('/access_token=:accessToken', {
template: '',
controller: function ($location, $routeParams, AuthService) {
AuthService.login( // `AuthService` will save the token
$routeParams.accessToken); // The token is available in `$routeParams
// under the key `accessToken`
$location.path('/'); // Redirect to the default route
$location.replace(); // For better UX, remove this route from history
}
})
See, also, this short demo.
Or navigate directly to this URL for a live demo:
http://fiddle.jshell.net/ExpertSystem/N8CgC/show#access_token=12345.

AngularJs $location.path with full url

I want to route the user to an url if he clicks ok in a modal. In my controller i receive urls like
var newUrl = http://localhost:3000/#/dashboard
var newUrl = http://localhost:3000/#/users
as variable.
If i then use
$location.path(newUrl);
it does not work. I also tried
$location.url(newUrl);
but my URL gets encoded like this.
http://localhost:3000/#/#%2Fdashboard
Is there a way to get only the path of the url?
Edit
this code is part of a service. A user make some inputs in a form and clicks on another link for example in the menu. Then a popup appears where he is asked to skip his form changes. If he clicks yes i get the requested url. This is from my development environment on the server of course it will be another url. So i can not just use
$location.path("/users")
for example
I ran into this same problem when having Angular preventDefault $locationChangeStart events, force a save, and only redirect upon success. I define the following function in the body of the controller:
var baseLen = $location.absUrl().length - $location.url().length;
function getPath(fullUrl) {
return fullUrl.substring(baseLen);
}
It doesn't seem like a clean solution, but as a work around, it does the job. A RegEx might work better for you, if you don't know that your URLs are pointing to the same site.
You can use $location.absUrl().
See the official documentation: enter link description here
This method is getter only.
Return full url representation with all segments encoded according to rules specified in RFC 3986.
May I offer a different solution:
$scope.$on('$locationChangeStart', function(e) {
if (meetsTheRequirementsToLeave()) {
return;
}
var newPath = $location.path();
e.preventDefault();
checkIfUserWantsToLeave().then(function() {
$location.path(newPath);
});
});
Within this event $location.path() returns the new path.

AngularJS - How can I do a redirect with a full page load?

I want to do a redirect that does a full page reload so that the cookies from my web server are refreshed when the page loads. window.location = "/#/Next" and window.location.href = "/#/Next" don't work, they do an Angular route which does not hit the server.
What is the correct way to make a full server request within an Angular controller?
For <a> tags:
You need to stick target="_self" on your <a> tag
There are three cases where AngularJS will perform a full page reload:
Links that contain target element
Example: link
Absolute links that go to a different domain
Example: link
Links starting with '/' that lead to a different base path when base is defined
Example: link
Using javascript:
The $location service allows you to change only the URL; it does not allow you to reload the page. When you need to change the URL and reload the page or navigate to a different page, please use a lower level API: $window.location.href.
See:
https://docs.angularjs.org/guide/$location
https://docs.angularjs.org/api/ng/service/$location
We had the same issue, working from JS code (i.e. not from HTML anchor). This is how we solved that:
If needed, virtually alter current URL through $location service. This might be useful if your destination is just a variation on the current URL, so that you can take advantage of $location helper methods. E.g. we ran $location.search(..., ...) to just change value of a querystring paramater.
Build up the new destination URL, using current $location.url() if needed. In order to work, this new one had to include everything after schema, domain and port. So e.g. if you want to move to:
http://yourdomain.example/YourAppFolder/YourAngularApp/#/YourArea/YourAction?culture=en
then you should set URL as in:
var destinationUrl = '/YourAppFolder/YourAngularApp/#/YourArea/YourAction?culture=en';
(with the leading '/' as well).
Assign new destination URL at low-level: $window.location.href = destinationUrl;
Force reload, still at low-level: $window.location.reload();
After searching and giving hit and trial session I am able to solove it by first specifying url like
$window.location.href = '/#/home/stats';
then reload
$window.location.reload();
I had the same issue. When I use window.location, $window.location or even <a href="..." target="_self"> the route does not refresh the page. So the cached services are used which is not what I want in my app. I resolved it by adding window.location.reload() after window.location to force the page to reload after routing. This method seems to load the page twice though. Might be a dirty trick, but it does the work. This is how I have it now:
$scope.openPage = function (pageName) {
window.location = '#/html/pages/' + pageName;
window.location.reload();
};
Try this
$window.location.href="#page-name";
$window.location.reload();

Resources