Angular 6 route params reload after Location.go - javascript

In order to avoid any component reload I'm using Location.go to change the URL from my first Component (SearchboxComponent).
The thing is that I'm using the route params in a second Component (ListingComponent) to reflect the URL changes in some links, pagination etc. But the new URL is not detected by my subscription and the params don't change. Can I make the router module reparse the URL to fill the new params?
ListingComponent
this.route.params.subscribe( async (params: IListingUrlParams) => {
console.log('params', params);
});
SearchboxComponent
const url = this.parametersService.searchParamsToUrl(params);
// this.router.navigate([url]); This works but reloads my main component
this.listingsService.getList(params); // Fetch the new data before navigation
Location.go(url); // This works but params are not reloaded

If you want to update your current route parameters.
Lets say your route as:
path/:id
Current path : path/123
in component:
import { Location } from '#angular/common';
constructor(private location: Location) { }
updateRoute(){
let url = this.location.path().replace('123', '456');
this.location.go(url);
}
Updated path : path/456

Related

Read route params Angular

I'm working with Paypal API that after confirming the purchase it redirects to the url you want, I put the url that I wish would be "localhost:4200/shop/order".
however whenever paypal returns the url, they add the token and payerid at the end url
"localhost:4200/shop/order?token=8YS089366D9655&PayerID=ASDVD4BLMH",
however when it comes back to my angular application, i have an error saying that the page cannot be found.
I have tried several ways to configure the route, but all attempts have failed.
idk if Angular dont accept "?" and "&" in route.
const shopRoutingConfig:Routes = [
{
path:'',component:ShopAppComponent,
children:[
{path:'purchase',component:PurchaseComponent},
{
path:'order/:token/:payerid', //fail in url returned from paypal
component:OrderComponent
}
]
}
]
#NgModule({
imports:[
RouterModule.forChild(shopRoutingConfig)
],
exports:[RouterModule],
})
export class ShopRoutingModule{}
my order component:
export class OrderComponent implements OnInit
{
constructor(private route:ActivatedRoute) {
}
ngOnInit(): void {
debugger
const routeParams = this.route.snapshot.paramMap;
var tokenText = routeParams.get('token')
var userId = routeParams.get('PayerID')
}
}
the only way that worked , is if i edit url manually to
"localhost:4200/shop/order/8DC695025P9917207"
"localhost:4200/shop/order?token=8YS089366D9655&PayerID=ASDVD4BLMH" token and PayerId is query params, but you have described your route as order/:token/:payerId, which is Route params.
so it would have been worked if redirection URL would be
"localhost:4200/shop/order/8YS089366D9655/ASDVD4BLMH".
Since redirection URL is returning with queryParams, it would be better to set your route as
path:'order/', component: yourComponent
and in component.ts
constructor() {
this.route.queryParams.subscribe(params => {
this.tokenText = params.token:
this.userId = params.payerId
})
}

How to update value from Router params inside component?

I'm using Angular5.
I have Header component.
Goal: I need to implement breadcrumbs in header.
My view:
Routing already implemented, I just need to:
parse ID from URL
get Item from BackEnd
get Name
set Name as Breadcrumb to Header component
My current progress:
I can parse ID from URL using following code:
this.activatedRouter.params.subscribe(params => {
this.id = params['id'];
});
Now, in template I have:
<ul class="breadcrumb">
<li><a routerLink="/items" routerLinkActive="active">Items</a></li>
<li>{{id}}</li>
</ul>
Question: How to update ID value in Component each time after new route executed?
For example:
I'm on Items Page => My URL localhost:4002/items
I clicked on Item, and redirected to Items page => My URL localhost:4002/items/34 => My Breadcrumbs = Items > 34
Thanks in advance
you can use :
constructor( private route: ActivatedRoute) {}
this.route.routerState.params.subscribe(params => {
this.id = params['id'];
});
your component will be updated with the new state
I found solution
constructor(private router: Router) {
this.router.events.subscribe((val: NavigationEnd) => {
...action with val.url variable
}
}
Each time, after redirect you will get data from your URL.

ember normalizeResponse when navigated to page from link-to

When I navigate to a specific page, the overridden function normalizeResponse in my serializer used in conjunction with code in my router model function, to add meta data to my model, works correctly. Basically, normalizeResponse runs first, then my model function in my router.
serializers/application.js
import App from '../app';
import JSONAPISerializer from 'ember-data/serializers/json-api';
App.storeMeta = {};
export default JSONAPISerializer.extend({
normalizeResponse(store, primaryModelClass, payload){
App.storeMeta[primaryModelClass.modelName] = payload.meta;
return this._super(...arguments);
}
});
And in my model.
import App from '../app'
...
model(params){
const data = {};
return this.store.findRecord('myModelType', params.id).then((myModelType)=>{
myModelType.meta = App.storeMeta['myModelType'];
return myModelType;
},()=>{ //error
this.get('session').invalidate();
});
}
When I navigate to that specific page through a link-to from another page, the model code gets called first, so there is no meta data being attached to the model.
How do I get the normalizeResponse function to run before the model function when navigated to from link-to?
Any help would greatly be appreciated.
The answer for anyone who sees this is to add {reload: true} as a param to the findRecord function.
So the second code snippet from my original post would know look like the following:
import App from '../app'
...
model(params){
const data = {};
return this.store.findRecord('myModelType', params.id, {reload: true}).then((myModelType)=>{
myModelType.meta = App.storeMeta['myModelType'];
return myModelType;
},()=>{ //error
this.get('session').invalidate();
});
}
More info here. Thanks to that site for the answer.

How to hold URL query params in Vue with Vue-Router

I am doing a project in Vue with Vue-Router . in my project ,i have a param named 'adtag' , which must be in the url query params , is there any simple way to hold this param ,no mater how router goes.
for example , I have three pages:
localhost/index
localhost/list
localhost/detail?id=11
page change using vue-router <router-link :to="{name:'Detail',query:{id:item.id}}"></router-link>
if I opened first page localhost/index?adtag=123 with adtag,page will changes with param 'adtag'
localhost/index?adtag=123
localhost/list?adtag=123
localhost/detail?adtag=123&id=11
With a default Vue 2.x installation, the router file is located src/router/index.js
I was able to then check if I needed to modify the request and add in any missing query params (modifying the to var apparently has no effect), and then call a "redirect" of next( .. new rout.. ).
Downside: Doubles the route calls, because essentially it redirects
Upside: It works, and the query preserving logic is in one place.
One caveat: On page load, the router fires and the "from" is a very empty route (even excluding the query params that were in the URL). Therefor I setup that if statement to verify the need to place the query param in place.
import Vue from 'vue'
import Router from 'vue-router'
// ... All your other components
Vue.use(Router)
const router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'Dashboard',
component: Dashboard
},
// ... All your other routes
]
})
router.beforeEach((to, from, next) => {
if (from.query.token && !to.query.token) {
if (to.path === from.path) {
// console.log('Identical routes detected')
return // This is a no-no via the documentation, but a bug in routing to identical routes strips query params, and this prevents that
}
next({path: to.path, query: {token: from.query.token}})
}
next()
})
export default router
As this is still an issue, I would even recommend using next(false) instead of returning.
if (from.query.foo && !to.query.foo) {
if (from.path === to.path) {
next(false);
} else {
next({
path: to.path,
query: { ...to.query, foo: from.query.foo },
});
}
} else {
next();
}
For reference, the same issue from the github repository: https://github.com/vuejs/vue-router/issues/1900#issuecomment-346531301.

How do I set/read a query string when using the router in aurelia?

When using the aurelia.io framework router, what is the preferred method for reading and setting a query string?
For example, in the url: http://www.myapp.com/#/myroute1/?s=mystate
How do I read and set the ?s=mystate part of the url and have the aurelia router navigate correctly and remember that state, such that whenever I arrive in my route1 viewmodel I can read that state variable and do something with it?
On viewmodel you can implement method activate(params, routeConfig) and object params should contain your query variables
activate(params, routeConfig){
console.log(params.s); //should print mystate
}
To navigate to some route, you have to specify the name of this route in app.js (name: 'redirect')
config.map([
{ route: ['','welcome'], moduleId: './welcome', nav: true, title:'Welcome' },
{ route: 'flickr', moduleId: './flickr', nav: true, title:'Flickr' },
{ route: 'redirect', moduleId: './redirect', name: 'redirect'},
{ route: 'child-router', moduleId: './child-router', nav: true, title:'Child Router' }
]);
and then use method NavigateToRoute with parameters.
router.navigateToRoute('redirect', { s:'mystate'}, {replace: true});
If you want to change queryParams and reload page with it (e.g. change page number on pagination link click) -- you must use determineActivationStrategy with replace.
Create view model and add determineActivationStrategy function:
import {activationStrategy} from 'aurelia-router';
export class ModelView{
determineActivationStrategy() {
return activationStrategy.replace;
}
}
Add activate event to your model for saving params:
activate(params, routeConfig, navigationInstruction){
this.queryParams = params ? params : {};
}
Add code for reload or navigate with same or new parameters:
moveToNewPage(newPageNumber){
this.queryParams.page = newPageNumber; // change page param to new value
this.router.navigateToRoute(this.router.currentInstruction.config.name, this.queryParams);
}
P.S. for this.router access use inject and don't forget to set name of router in app configuration:
import {Router} from 'aurelia-router';
export class ModelView{
static inject() { return [Router] };
constructor(router){
this.router = router;
}
}
As per the latest configuration, the query string will not be retrieved if you didn't set the push state.
Set push state to true. and add base tag in index.html.
<base href="http://localhost:9000/"> - index.html
config.options.pushState = true; - app.js -> configureRouter method.

Categories

Resources