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

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.

Related

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 4: ionic serve reloads app on every page

I'm new to Ionic 4 and I'm trying to figure out if I'm doing something wrong, or if Ionic 4 just acts differently in this area. I have a very simple app that just has a few Ionic pages, and in the app.component.ts file I trigger some init logic in the platform.ready() call. I noticed this init code was fired on every page load when testing via ionic serve. Some code is below. I assume ionic serve is supposed to only reload the app when the code changes (and not on every navigation to a new page)? Maybe my navigation approach is causing the app to reload?
app.component.ts
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar
) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(async () => {
this.statusBar.styleDefault();
this.splashScreen.hide();
let time = new Date().toLocaleString();
console.log(`${time}: Platform is ready...dude`);
});
}
Simple navigation that loads various empty pages (and seems to trigger an app reload on every nav).
Home.page.html
<ion-content padding>
<h1>Home Page</h1>
<ul>
<li>HOME</li>
<li>login</li>
<li>profile</li>
<li>signup</li>
<li>accounts</li>
<li>admin</li>
</ul>
</ion-content>
app-routing.module.ts
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', loadChildren: './pages/home/home.module#HomePageModule' },
{ path: 'login', loadChildren: './pages/login/login.module#LoginPageModule' },
{ path: 'profile', loadChildren: './pages/profile/profile.module#ProfilePageModule' },
{ path: 'account-detail/:id', loadChildren: './pages/account-detail/account-detail.module#AccountDetailPageModule' },
{ path: 'account', loadChildren: './pages/account/account.module#AccountPageModule' },
{ path: 'settlement', loadChildren: './pages/settlement/settlement.module#SettlementPageModule' },
{ path: 'signup', loadChildren: './pages/signup/signup.module#SignupPageModule' },
{ path: 'admin', loadChildren: './pages/admin/admin.module#AdminPageModule' },
];
Rookie mistake. I'm posting an answer in case anyone else stumbles into this.
My issue was the anchor tags. Obviously I'm unfamiliar with the angular router. Looks like if you provide a routerLink it will do what we'd expect from a "normal" SPA link (as opposed to reloading the app).
Updated Home Page
<ion-content padding>
<h1>Home Page</h1>
<ul>
<li><a [routerLink]="['/home']" routerDirection="root">HOME</a></li>
<li><a [routerLink]="['/login']" routerDirection="root">login</a></li>
<li><a [routerLink]="['/profile']" routerDirection="root">profile</a></li>
<li><a [routerLink]="['/signup']" routerDirection="root">signup</a></li>
<li><a [routerLink]="['/account']" routerDirection="forward">accounts</a></li>
<li><a [routerLink]="['/admin']" routerDirection="forward">admin</a></li>
</ul>
</ion-content>

How to Move from one page to another in ionic 4?

I want to move from 1 page to another page and for that I have write below code in home.page.html file.
<div style="display: flex; justify-content: center; margin-top: 20px; margin-bottom: 20px;">
<ion-button (click)="goToLoginPage()" size="large">Continue</ion-button>
</div>
Below is home.page.ts file code.
export class HomePage {
constructor(public navController: NavController) {
}
goToLoginPage(){
this.navController.navigateForward(LoginVCPage) // Getting error at this line.
}
}
Below is error screenshot.
Any help will be appreciated
In Ionic 4 using NavController is deprecated. See this statement from the Migration Guide:
In V4, navigation received the most changes. Now, instead of using
Ionic's own NavController, we integrate with the official Angular
Router.
Angular manages it's routes in a separate file, in Ionic 4 this file is named app-routing.module.ts. Every time you create a new page using ionic g page pagename the CLI will automatically create a new entry in the routes array in app-routing.module.ts.
So assuming you have created a test page and now have following routes in app-routing.module.ts:
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', loadChildren: './home/home.module#HomePageModule' },
{ path: 'test', loadChildren: './test/test.module#TestPageModule' },
];
You can move to another page by adding a href property to your button with the corresponding path (e.g. '/test') to the page you want to move to:
<ion-button href="/test">Move to test page</ion-button>
You could also use the routerLink directive as pointed out here:
<ion-button [routerLink]="['/test']">Move to test page</ion-button>
If you want/need to navigate programmatically you'll have to inject the router service into your page/component and call navigateByUrl like so:
constructor(private router: Router) { }
goToTestPage() {
this.router.navigateByUrl('/test');
}
Also see the Angular docs on routing and the Ionic v4 docs on this topic.
To add to #Phonolog 's answer you should also use routerDirection="forward" or whatever direction it may be.

Angular 5 Routing - Navigate to route by typing URL into address bar returns Handler for Request not found (404)

I am using Angular 5 to talk to a Service Stack back end.
I can load my home page by typing in the root address: http://127.0.0.1:8088 and from there I can navigate to all my defined routes using the relevant links.
However if I try to manually type in a route, i.e. http://127.0.0.1:8088/home or http://127.0.0.1:8088/searcharchive I get:
Handler for Request not found (404):
Request.HttpMethod: GET
Request.PathInfo: /home
Request.QueryString: Request.RawUrl: /home
My routing codes is as follows:
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'searcharchive', component: SearchArchiveComponent },
{path: '', redirectTo: 'home', pathMatch: 'full'},
{path: '**', component: PageNotFoundComponent}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
And the HTML template is:
<nav>
<a [routerLink]="['/home']">Home</a>
<br/>
<a [routerLink]="['/searcharchive']">Search Archive</a>
<br>
<div class="container-admin-nav">
<a [routerLink]="['/admin']">Admin Module</a>
</div>
</nav>
This is causing a real headache as not only can I not navigate using the address bar I cannot even do simple things like adding images, as no matter where I place the image It can't be displayed. When looking at the developer tools I get GET http://127.0.0.1:8088/logoTransparent.png 404 (Not Found) so I can only surmise that routing is (once again) getting in the way some how.
I had a similar problem because I was using
proxy configuration.
Angular app was my front-end and I had a SpringBoot app as back-end.
In my proxy.config.json file I had the following:
{
"/**": { <-- **marked line**
"target": {
"host": "localhost",
"protocol": "http:",
"port": 8080
},
"secure": false,
"logLevel": "debug"
}
}
So, whenever I typed in any route in the address bar, it would get rerouted to my SpringBoot app because of the marked line... and I didn't want that. I just wanted my back-end requests from my services to be rerouted to my back-end.
Solution:
I added /api to my back-end requests (in all my services) and then, in proxy.config.json I just removed /api from the url. To achieve this, I just added "pathRewrite": { "^/api": "" }, to my proxy.config.json which now looked like this:
{
"/api/**": {
"target": {
"host": "localhost",
"protocol": "http:",
"port": 8080
},
"pathRewrite": {
"^/api": ""
},
"secure": false,
"logLevel": "debug"
}
}

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