Angular 7 Router - Navigate without adding to the history - javascript

Using Angular Router, I want to navigate to another url without adding it to the browser history.
this.router.navigateByUrl(`${pathWithoutFragment}#${newFragment}`);
Can I do it with only Angular?

Thanks to NavigationExtras you can now use replaceUrl: boolean inside navigate()
This will replace the current url, and the new URL will update in the address bar:
this.router.navigate([`/somewhere`], { replaceUrl: true });
That way when you press back it will not remember the previous page in the history.

As #IngoBürk Mentioned in the comment you can achieve the same result without using skiplocationChange
this.router.replaceUrl('path')
skipLocationChange
Navigates without pushing a new state into history.
this.router.navigateByUrl([`${pathWithoutFragment}#${newFragment}`], { skipLocationChange: true });
Ref:https://angular.io/api/router/NavigationExtras#skipLocationChange

Related

Change router URL without navigating, but add to browser history

I have a search page, where the user can perform a search and see a result.
Initially, my issue was to update the router URL without navigating, but I solved that by using "Location".
My ngOnInit - my search page can be navigated to by another page, so I listen for queryParams to perform the search if any happens:
ngOnInit() {
this.queryParamsSubscription = this.activatedRoute.queryParams.subscribe(queryParams => {
this.searchText = queryParams[TD_QUERY_PARAMS.text];
if (this.searchText) {
this.search();
}
});
}
my search method:
search() {
const queryParams: Params = { text: this.searchText };
const desiredUrl = this.router.createUrlTree([], {
queryParams: queryParams,
relativeTo: this.activatedRoute,
skipLocationChange: true
});
this.location.replaceState(desiredUrl.toString());
}
This implementation makes sure that I update the URL when the user searches within the search page, which was the first part of my solution.
However, I also want to add any search to the browser history, ie:
I start by launching my application on 'localhost:4200/landing'.
On this page, I have a search bar, that when triggered will navigate to my search page.
From the landing page, I search for '1'. The router then navigates to: 'localhost:4200/search?text=1'
Then on the search page, I search for '2'. the search is performed, and the URL is updated to: 'localhost:4200/search?text=2'
Finally I search for '3': ''localhost:4200/search?text=3'.
When I then press the browsers 'Back' button, I would expect to be navigated to ''localhost:4200/search?text=2'.
However, none of the searches I made within the page has been added to history, so I will be navigated to whatever page I was accessing before the search page. In my case, 'localhost:4200/landing'.
How can I add each of these searches to the browsers history?
I believe that one of these is what yo need:
this.router.navigate(['/yourRouteGoesHere'], { replaceUrl: true });
The other options that you have is to use: SkipLocationChange this.router.navigateByUrl(['yourFullPath'], { skipLocationChange: true });
use this.router.replaceUrl('path').
That way you can navigate, without adding this route to history.
This was a case of way overthinking the issue I was facing.
By just using router.navigate(['/search'], { queryParams: queryPrams })
I got the result I desired. The URL was changed, a point was added to browser history.
What I failed to realize, was that router.navigate, will not reload the entire page, when only the queryParams are changed.
Hope this helps anyone struggling with the same issue.

Vue $route.push not working when called from method

I'm building a search bar for my app with vue-bootstrap-typeahead autocomplete lib, if your not familiar with it, when you click a suggested result it triggers the #hit event, passing the result data to the method.
<vue-bootstrap-typeahead
...
#hit="goToResult"
...
/>
Then I have the goToResult method
methods: {
goToResult(result) {
this.$router.push({name: 'market', params: {marketId: result.id}});
},
...
}
When I do search from a non-market route it works fine, redirecting the user to the desired /market/:marketId route, but when it's done from a "market" route it just changes the URL but doesn't redirects to the new market, it even triggers the "duplicated route" error if I click the same result twice, but still not redirecting.
Any suggestion?
Thanks
Check out the note at the bottom of the router.push section: https://router.vuejs.org/guide/essentials/navigation.html
Note: If the destination is the same as the current route and only params are changing (e.g. going from one profile to another /users/1 -> /users/2), you will have to use beforeRouteUpdate to react to changes (e.g. fetching the user information).
...and here is how to use beforeRouteUpdate:
https://router.vuejs.org/guide/essentials/dynamic-matching.html#reacting-to-params-changes
Hope this helps!

Ember - abort the route and reload the route with same model

In my ember app, when the user clicks the Back button of browser,I need to stop the transition (whereever it might take me as per Ember history) and reload the same url with same model. Have tried the below code, but doesnt seem to work:
search-route.js
var route = Ember.route.extend({
actions:{
willTransition: function(transition){
if(this.controller.get('order') === 1){
transition.abort();
this.transitionTo('search',model)
}
}
}
})
This doesnt seem to work and gives error about query params. So, i looked for what is there in transition object. Saw that as soon as I enter this code, the object transition contains prop queryParams but with the old values, not the current URL one. But there is another prop - transition.intent.preTransitionState.fullQueryParams which contains the current URL query params. Would that be used here somehow.
I looked for solutions and someone also suggested to put in this.refresh(), but also didn't work.
I'm trying on my own ember app and doing a transition.abort() followed with a this.refresh() works.

In angular js what is the best way to reload a state everytime the app goes to that state?

I can use javascript functions like window.location().But can also use $state.go and $state.transitionTo methods of angularjs.But using the angularjs $state service, the state doesnt reload everytime.I need to reload the state everytime the app enters that state through the angular ui router and the view should also be updated everytime.Do i have to use the more native window.location method?
Please this is important as the $state service methods are not reloading the state everytime
I followed the link Reloading current state - refresh data .But the inherit:false property value in the transitionTo method is not reloading the state everytime on my app end.Maybe it has to do something with cache.
What i want to achieve is that after editing a form it will go the listing state and show the updated values in that state which i updated through the form.But in that state it is still showing the previous values.ie. the state is not reloading everytime and the values are not updating everytime
This is the controller code:
EditUser.workat(company_form,$scope.userId).then(function(response){
console.log(response);
$scope.hide();
if(response.data.is_success) {
$scope.company_form = response.data.company_address_info;
//$state.go('about', {user_id: $scope.userId}, {reload: true});
$state.transitionTo('about', {user_id: $scope.userId}, {
reload: true,
inherit: false,
notify: true
});
}else{
$ionicPopup.alert({
title: 'Error',
content: response.data.message
});
}
});
In html :
<a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
In Javascript
$state.go('name', {reload:true});
https://github.com/angular-ui/ui-router/wiki/Quick-Reference
Actually I'm taking a guess here because there are not enough infos regarding what you want to achieve.
The native ui-router reload method is:
$state.reload()
or:
$state.go('YOUR.STATE', {reload:true});
That will reload your current state.
Still though this is seems not a god approach (to reload the state every time but still there are no enough infos related with you goal and source.

Getting state from URL string with Angular UI Router

I'm using state-based routing (Angular UI Router v0.2.7) in a project and looking for a way to get the current state (name) from a given URL string.
Something like:
$state.get([urlString]) returns stateName:String or state:Object
I need this method to check if a state exists to a given URL because not all URLs are mapped to a state in my project. Using Play Framework as backend, some URLs (e.g., login form) are not mapped to a state because they using different templates then the Angular (main) part of my application.
For those "none-Angular" pages (i.e., not covered by a state) I would do a reload. To identify URLs not covered by a state I need the method mentioned above. Planned to do it like this:
$rootScope.$watch(function() { return $location.path(); }, function(newUrl, oldUrl) {
if(newUrl !== oldUrl) {
if (!$state.get(newUrl)) {
$window.location.assign(newValue);
}
}
}
Already checked the docu but there is no such method.
Any ideas?
It's all or nothing. If you plan to use ui-router make sure all your URLs resolve to a state. If the state doesn't exist it will go to the otherwise state. It's possible to have optional parameters.
An alternative is to use .htaccess redirects to catch the URL and redirect you before it hits the ui-router.
Provide more details and we can see what the best option is.
Try using this will get the current sate name.
var stateName = $state.current.name;

Categories