router.navigate is not working in Angular - javascript

bellow is my redirect method which is not working
goToProdPage() {
this.router.navigate([this.quoteId,'/cpq']);
window.location.reload();
}
but if i change this to
goToProdPage() {
this.router.navigate(['./'+this.quoteId+'/cpq']);
window.location.reload();
}
Then its working fine. but now i'm not able to get url param(which is quoteId) from activatedRoute in other components.
bellow is routing code in app.module.ts
const appRouter :Routes = [
{path:'login', component: loginPage},
{path:':quoteId/cpq', component: cpqPage},
{path:'', redirectTo:'/login', pathMatch:'full'},
]

You donĀ“t need window.location.reload(); which will skip the cache and reload the same page, change it as
goToProdPage() {
this.router.navigate([this.quoteId, 'cpq']);
}

Related

Best way to check what page you're on in Vue.js

I have
these simple route/URL when I am in a car details page
http://localhost:8080/car/1
I am using vue2; what is the best way to check if I am on a car page?
I normally
would have checked for the first segment of the URL, but I wasn't sure if that is the best future-proof approach.
Questions
Should I use JS to detect what page I am ?
Should I use Vue functionality to access the router object?
Why would one decide to pick one over another?
You could provide a name for your route inside the routes definition like :
{
path: '/car/{id}',
name: 'car',
component: CarView
},
then access it using this.$route.name or you could parse the this.$route.path to get the name using String object methods
Perhaps, try using: router.currentRoute.path, where router is:
import Router from "vue-router";
Vue.use(Router);
const routes = [
{ path: "/", component: Home },
{ path: "/test1", component: Test1 },
{ path: "/test2", component: Test2 }
];
const router = new Router({
routes
});
console.log('Current route: ', router.currentRoute.path);

ChunkLoadError / Unhandled Promise rejection Ionic 5 /angular

I am trying to add offline functionality to my ionic 5 app. For that, I implemented a logic of storing information in sql lite while conected, and when offline bring data from sql lite instead of http request.
obtenerVisitaDetalle(idVisita: number): Observable<any> {
if (this.networkService.getCurrentNetworkStatus() == ConnectionStatus.Offline) {
return from(this.getLocalData(`Visita/${idVisita}`));
} else {
return this.http.get<any[]>(environment.UrlBaseApi + `Visita/${idVisita}`, this.httpOptions).pipe(
tap(res => {
this.setLocalData(`Visita/${idVisita}`, res);
})
)
}
}
So far so good, but I came across the following problem:
https://github.com/ionic-team/ionic-framework/issues/20859
Basically when I am offline, I am unable to open components like modal, since those have not been preloaded. Comment on link above mention using service worker to prefetch the chunks/assets you need ahead of time.
Any guidance, example on how to acomplish this, will be appreciated. Thanks
Edit: Based on first answer I am providing part of the routing file.
{
path: 'pago',
canActivate: [UserAuthenticatedGuard],
loadChildren: () => import('./Pages/pago/pago.module').then( m => m.PagoPageModule)
}
];
#NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
Preloading is supported from Angular Cli V6 so you might want to look into https://angular.io/api/router/PreloadAllModules. Basically you can preload all your modules by adding the following to your RouterModule.
RouterModule.forRoot(
routes, { preloadingStrategy: PreloadAllModules ,}
),
Or you can preload specific routes by defining a custom PreloadingStrategy.
export class CustomPreloadingStrategy implements PreloadingStrategy {
preload(route: Route, load: Function): Observable<any> {
return route.path == 'YOUR_PATH' ? load() : of(null);
}
}

url changes but angular does not navigate

I have 2 links like below. When I click on any one the first time, it navigates to it but when I click on the second link after that, the url changes but it does not navigate to it.
<li><a routerLink="/order/buyer" >Buyer</a></li>
<li><a routerLink="/order/seller">Seller</a></li>
These are my route configuration:
app.routing.module.ts
const routes: Routes = [
{
path: '',
pathMatch: 'full',
component: RootComponent,
},
{
path: '',
children: [
{
path: 'order',
loadChildren: './order/order.module#OrderModule',
}
]
}
order.module.ts
export const ROUTES: Routes = [
{
path: ':orderParty/:id',
component: OrderDetailComponent,
canDeactivate: [OrderDetailGuardService]
},
{
path: ':orderParty',
component: OrderListComponent
}
];
Tried several things, that out there but didn't work. What I have noticed is on the second click, the ngOnInit() of the 'OrderListComponent' does not get called.
You have a few options to solve this common issue in Angular, the most common one is using the solution on this GitHub thread:
https://github.com/angular/angular/issues/13831#issuecomment-319634921
constructor(private router: Router){
// override the route reuse strategy
this.router.routeReuseStrategy.shouldReuseRoute = function(){
return false;
}
this.router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd) {
// trick the Router into believing it's last link wasn't previously loaded
this.router.navigated = false;
// if you need to scroll back to top, here is the right place
window.scrollTo(0, 0);
}
});
}
Another solution would to subscribe to your router params and handle change based on the new param like this article suggests:
this.activeRoute.params.subscribe(routeParams => {
this.loadUserDetail(routeParams.id);
});
https://medium.com/#mvivek3112/reloading-components-when-change-in-route-params-angular-deed6107c6bb
Yes, because route is same its the dynamic parameter that is changing. to read changed parameter you can inject router in construct and read parameter like
this.router.params.subscribe((params)=>{console.log(params)});
The route is pointing to same component hence its not re initializing.

Angular - How can I activate AUX route with lazy loaded module?

I have an angular app which is loading lazily module.
At first the app is navigating to home where it loads the module ( named module1) :
main routing :
const routes: Routes = [
{ path: "", redirectTo: "/home", pathMatch: "full" },
{ path: "home", loadChildren: "./module1/module1.module#Module1Module" },
];
At module1 - there's also routing table :
const routes: Routes = [
{
path: "", component: Home1Component,
children: [
{ path: 'bird', outlet: 'under', component: Home2Component }
]
}
];
So since it's loading lazily , when the app starts - it goes to /home where there it loads the Home1Component
But Home1Component also has a button in it which suppose to set a value to the outlet route .
home1.component.html:
<input value="click to activate aux route" type="button" (click)="go()"/>
<router-outlet ></router-outlet>
<router-outlet name='under'></router-outlet> //<---- I want to activate only this
This is how I try to activate the outlet route :
public go() {
this.router.navigate([{ outlets: { under: ['bird'] } }], { relativeTo: this.route })
}
But I get an error :
Error: Cannot match any routes. URL Segment: 'home'
Question :
Why am I getting this error and how can I fix it ?
Online code here : Stackblitz
Well with the help of #jmw5598 who referenced me to the problem/bug with the router .
There is a problem with default empty location for lazy loaded modules.
Here is a working solution for the problem .
The key thing to understand is that lazy modules should not have empty root path
Related specific description :

Vue-Router Duplicate Page

I'm in trouble with vue-router :) I create a simple map for router :
module.exports = {
'/': {
component: require('./views/home')
},
'/auth/login': {
component: require('./views/auth/login')
},
'/auth/register': {
component: require('./views/auth/register')
},
'/resumes': {
component: require('./views/resumes')
},
// 404 NotFound
'*': {
component: {
template: "not found"
}
}
};
And define router to vue and it works perfectly. My home page js codes :
module.exports = {
inherit: true,
template: require('./template.html'),
ready: function() {
if(this.isLoggedIn)
this.$route.router.go('/resumes');
}
};
I want to load resumes page if user logged in.
When I use it in any event or with v-link directive, it works normal.
But if I use it on ready function, it duplicates pages. It calls home page and appends second page on it.
IMG : http://imageshack.com/a/img540/9409/3DK1ZL.jpg
Whats wrong? How can I solve it? I am dealing about 4 days with this problem. Please help me guys.
this.$route.router.go('/resumes') has already been removed since Vue 2.0.

Categories