Angular 7: unwanted redirect when query parameters are present - router

I use #angular/router with angular 7.
My goal is to use an arbitrary number of (optional) query parameters on one of my pages, in particular in /pages/components
The problem I face is that whenever I enter some query parameters in my URL bar, I get redirected to a weird location. This redirect happens for all my pages, if any query parameter is present.
Example:
http://localhost:4200/pages/dashboard (works fine)
http://localhost:4200/pages/components (works fine)
http://localhost:4200/pages/dashboard?hello=55&world=77 : not working. I get redirected to http://localhost:4200/pages/components/lo%3D55&world%3D77
I am struggling to make sense out of this redirection.
It looks like the first query parameter has its first 3 letters cut off, the rest of the query string is escaped, and for some reason I always end up in /pages/components/something, even if the url that I typed was a totally different page (maybe because components-page is my only page with a parameter on the RouterModule?).
Here is my routing module:
const appRoutes: Routes = [
{path: '', component: LoginPageComponent, runGuardsAndResolvers:'always', pathMatch: 'full'},
{path: 'pages/components', component: ComponentsPageComponent, runGuardsAndResolvers: 'always'},
{path: 'pages/classes', component: ClassesPageComponent, runGuardsAndResolvers: 'always'},
{path: 'pages/components/:id', component: ComponentsPageComponent, runGuardsAndResolvers: 'always'},
{path: 'pages/dashboard', component: DashboardPageComponent, runGuardsAndResolvers: 'always'},
{path: 'pages/users', component: UserAdminisitrationComponent, runGuardsAndResolvers: 'always', canActivate: [UserRoleGuardService]},
{path: 'pages/reports', component: ReportsPageComponent, runGuardsAndResolvers: 'always'},
{path: 'pages/jobs', component: JobsPageComponent, runGuardsAndResolvers: 'always'},
{path: 'pages/material', component: MaterialPageComponent, runGuardsAndResolvers: 'always', canActivate: [UserRoleGuardService]},
{path: '**', redirectTo: '/pages/dashboard', pathMatch: 'full'}
];
#NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}

I had the same problem with Angular 8,
i was doing that :
this.returnUrl = this.route.snapshot.queryParams['returnUrl']
....
this.router.navigate([this.returnUrl]);
when this.returnUrl = "/my-componenet?x=4"; for example i was redirected to "/my-componenet%3Fx%3D4" instead.
the fix was to use navigateByUrl instead
i also added a decodeURI (just in case)
this.returnUrl =decodeURI(this.route.snapshot.queryParams['returnUrl'] || '/login')
....
this.router.navigateByUrl(this.returnUrl);

Related

How to load default Component in default App and next to do redirect to another sub app?

I Have 3 apps : root-config (single-spa), navbar-app ( port 4201 angular 12 ) angular-app (port 4202 angular 12 )
My root-config app (localhost:9000) has root-config.ts
registerApplication({
name: "#org1/myNavbarApp",
app: () => System.import("#org1/myNavbarApp"),
activeWhen: ["/"],
});
registerApplication({
name: "#org1/myAngularApp",
app: () => System.import("#org1/myAngularApp"),
activeWhen: ['/angular']
});
my myNavbarApp has app-routing.module.ts
const routes: Routes = [
{
path: 'login', component: LoginComponent,
}, {
path: 'menu',
component: MenuComponent,
},
{path: '**', component: EmptyRouteComponent}, // <-- will display angular app but will not
leave <mat-toolbar> in view from myNavBarApp ( only if i stay in localhost:4200/menu
and do refresh -> angular app default view displays under <mat-toolbar> of
myNavBarApp ( as expected behavior )
// {path: '**', redirectTo: 'login'}, // <-- renders default "login.component" on first load
of localhost:9000 (exactly what i need) but will cause next issue:
after navigateToUrl('angular') is done - ```login.component``` angular app content
are visible in the same page - ( not expected behavior )
];
const config: ExtraOptions = {
useHash: false,
enableTracing: false,
relativeLinkResolution: 'legacy',
};
#NgModule({
imports: [RouterModule.forRoot(routes, config)],
exports: [RouterModule],
providers: [{provide: APP_BASE_HREF, useValue: '/'}]
})
export class AppRoutingModule {
}
NavBarApp has menu.component.html includes next:
<mat-toolbar color="warn" class="toolbar">
<mat-button-toggle-group class="menu">
<mat-button-toggle (click)="singleSpaNavigateUrl('angular')" value="angular">Angular App</mat-button-toggle>
</mat-button-toggle-group>
</mat-toolbar>
and menu.component.ts includes next :
import {getAppNames, navigateToUrl, getMountedApps} from "single-spa";
public singleSpaNavigateUrl(url: string) {
console.log('appNames', getAppNames()); <-- IS ALWAYS EMPTY ARRAY , Why ?
console.log('mountedAppNames', getMountedApps()); <-- IS ALWAYS EMPTY ARRAY , Why ?
navigateToUrl('/'+ url); // <-- navigates to /angular
}
How to achieve myNavBarApp menu.component will stay visible in all child apps after login / or when is needed ?
How to achieve login.component as default , when myNavBarApp is loaded from root-config app in browser ( without entering "/login" manually after that)
Single spa documentation says: single-spa Layout Engine is optional at this time but is recommended if you foresee utilizing server side rendering .. So i do not have server rendering ...thats why i do not implement layouts , and want to know how it possible to do without it ?
Why getAppNames() and getMountedApps() returns always empty array ?

Angular routerLink routes properly but route.navigate in component routes to default path

The Basic Sample is created
The Source Code is Uploaded Here
and Deployed Here
A route is set with path :"products"
In app.template.html using routerLink directive a route is set ->
when "Products" gets clicked --> The route "products" is opened as
expected, but activating the same route through code
(this.route.navigate(['/products']) in "app.component.ts" navigates
to this 'home'.
This is basic but weird, where have I gone wrong ?
It's getting redirected on your app.component.html on line 19:
<a class="nav-link" href="#" (click)="navigateBack()"> Products(navigated in Component)</a>
This tag has href="#" so the page is getting routed to your root because your app-routing.module.ts file is redirecting to home.
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: '**', redirectTo: 'home', pathMatch: 'full' }
So, remove href="#" with [routerLink]="[]" and it should resolve the issue.

I can't redirect ionic page using tab forms

I can't redirect a ionic 4 tab page to other tab page using parameters.
I'm using tabs-routing.module.ts with this code:
{
path: 'tab2/:id',
outlet: 'tab3',
children: [
{
path: '',
loadChildren: () =>
import('../tab2/tab2.module').then(m => m.Tab2PageModule)
}
]
},
/* {
path: 'tab2/:id',
outlet:'tab3',
component: Tab2PageModule
}, */
The view contains:
ion-button size="small" href="/tabs/tab2/{{f}}/"...
or
ion-button size="small" href="/tab2/{{f}}/" ...
The browser says:
core.js:9110 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'tabs/tab2/1/'
When I use:
ion-button size="small" href="/tabs/(tab3:tab2/{{ f }})" ...
The url in browser is
http://localhost:8100/tabs/(tab3:tab2/2)
The content in the browser disappears and only shows the tabs.
To navigate within your app you should use routerLink directive like the following:
<ion-button size="small" [routerLink]="['/tabs/tab2/', id]">
routerLink directive documentation
It seems there is an other issue. Your declared routes are: tab2/:id and tab2/:id. Yet you're routing to /tabs/tab2/1 while you should be routing to /tab2/1
Like this:
<ion-button size="small" [routerLink]="['/tab2/', id]">
Thanks for your help, now it works correctly. However, now the controller does not get the parameter correctly.
In this screen I will call the details module
main module
But the module that receives the parameters does not get the data sent
This is how the screen looks without parameters
second module
When I add the complete code (using the parameter)
ion-button size=small routerLink=/tabs/tab2/{{f}}
ERROR Error: Uncaught (in promise): Error: Cannot match any routes.
URL Segment: 'tabs/tab2/3' Error: Cannot match any routes. URL
Segment: 'tabs/tab2/3'
The content of file tabs.routing.module.ts is
{
path: 'tab2/:id',
outlet: 'tab3',
children: [
{
path: '',
loadChildren: () =>
import('../tab2/tab2.module').then(m => m.Tab2PageModule)
}
]
},
{
path: 'tab2/:id',
outlet: 'tab3',
component: Tab2PageModule
},
the content of file tabs2.page.ts is
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { ListadoPokemonService } from '../servicio/listado-pokemon.service';
#Component({
selector: 'app-tab2',
templateUrl: 'tab2.page.html',
styleUrls: ['tab2.page.scss']
})
export class Tab2Page implements OnInit{
idPokemon: string;
nombrePokemon: string;
listado:any;
constructor(private activatedroute: ActivatedRoute, private servicio: ListadoPokemonService) { }
ionViewVillEnter(){
this.idPokemon = this.activatedroute.snapshot.paramMap.get('id');
// this.nombrePokemon = this.activatedroute.snapshot.paramMap.get('nombre');
this.servicio.getData('https://pokeapi.co/api/v2/pokemon/'+this.idPokemon+'/').subscribe(data=>{
console.log(data);
this.listado=data;
});
}
ngOnInit() {
}
}
Thanks in advance for your help i'm php & visual studio developer but new in angular & ionic issues.
I could solve it, just add the following code
{
path: 'tab2/:id',
//component: Tab2PageModule
loadChildren: () =>
import('../tab2/tab2.module').then(m => m.Tab2PageModule)
},
in tabs-routing.module.ts
I solved this problem by placing the redirect object above the empty path. like this example:
const routes: Routes = [
{
path: '',
redirectTo: '/user/profile-u',
pathMatch: 'full'
},
{
path: '',
component: UserPage,
children: [
{
path: 'job-applying',
loadChildren: () => import('./job-applying/job-applying.module').then(m => m.JobApplyingPageModule)
}, ...
I hope this helps you. I realize this seems like a trivial solution, but some things in this framework are just a little finicky.

ionic nav push params not shown in url

app.module.ts:
imports: [
IonicModule.forRoot(MyApp, {}, {
links: [
{ component: CategoryPage, name: 'Category', segment: 'category:id'}
]
}
],
providers: [
{
provide: LocationStrategy,
useClass: PathLocationStrategy
}
]
Configuration of the page I am navigating too
#IonicPage({
name: 'Category',
segment: 'category/:id'
})
Code which triggers navigation:
this.nav.push(CategoryPage, {id: 3});
The component does load as expected and I can call this.navParams.get('id') which yields 3 from within the components class.
Expected result: The url changes to /category:3
Observed result: The url changes to /category:id
so if you are trying to implement deep links for Ionic 3 (since Ionic 4 is using Angular's router by default now) you need to ensure you also configure each page accordingly.
The page you are navigating to needs to have configs added via #IonicPage:
#IonicPage({
segment: 'second/:id'
})
See more in ionic docs or this guide

Is Angular 2 Auxiliary router broken?

I'm trying to create an app with an auxiliary route for a chat window. The app fails right on the loading. It seems like a bug and I reported it on Angular GitHub, but I wonder if anyone knows a workaround? Here's the plunk of this simple app: http://plnkr.co/edit/JsZbuR
#Component({
selector: 'basic-routing',
template: `
<a [router-link]="['/Home']">Home</a>
<a [router-link]="['/ProductDetail']">Product Details</a>
<router-outlet></router-outlet>
<router-outlet name="chat"></router-outlet>
<a [router-link]="['/', ['Chat']]">Chat</a>
`,
directives: [ ROUTER_DIRECTIVES ]
})
#RouteConfig([
{path: '/', component: HomeComponent, as: 'Home'},
{path: '/product', component: ProductDetailComponent, as: 'ProductDetail' },
{aux: '/chat', component: ChatComponent, as: 'Chat'}
])
class RootComponent { /* ... */ }
It's not clear how the router knows which named route outlet to use.
You have to wait until the issue https://github.com/angular/angular/issues/4694 will be solved.
Current implementation allows only
this.router.navigateByUrl('/(chat)');
See the link http://plnkr.co/edit/lquMdagaVfIoAT83w1pl?p=preview