Problem to route to different components with Angular 8 - angular-routing

What I'm trying to do is to route to different components via the same path but it wont work.
/schedule -> shall load the ScheduleComponent
/schedule/123 -> shall load the EventComponent ('123' is a dynamic path, so that it is not an option to write it to children's path)
Here is the code:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { ScheduleComponent } from './schedule.component';
import { EventComponent } from '#app/modules/event/event.component';
const routes: Routes = [
{
path: '',
component: ScheduleComponent,
children: [
{
path: '**',
component: EventComponent
}
]
}
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ScheduleRoutingModule { }
But I'm doing something wrong and cannot find the mistake, because the EventComponent is called in any case, even if there is no additional path given. What is wrong with my code?
Thx!

You have not specified any routes in your code example.
The '**' path that you set is used for "page not found", in case a user navigates to a non existing route.
More on routes can be found in the official documentation
const routes: Routes = [
{ path: '/schedule', component: ScheduleComponent },
{ path: '/schedule/:id', component: EventComponent },
];

Related

Mongoose Error: Cannot read property 'length' of undefined in NestJs

I am using nests framework and versions of mongodb and mongoose are as specified below.
Please refer to the screenshot for error in detail.
versions
"mongodb": "4.0.0",
"mongoose": "5.5.12",
Error Screenshot
User Document Module
import { Module } from '#nestjs/common';
import { UserDocumentsService } from './user-documents.service';
import { UserDocumentsController } from './user-documents.controller';
import { MongooseModule } from '#nestjs/mongoose';
import { UserDocumentsSchema } from './schema/user-documents.schema';
#Module({
imports: [
// showing error on this line
MongooseModule.forFeature([
{ name: 'UserDocument', schema: UserDocumentsSchema },
]),
],
controllers: [UserDocumentsController],
providers: [UserDocumentsService],
})
export class UserDocumentsModule {}
App.module.ts
#Module({
imports: [
MongooseModule.forRootAsync({
imports: [SharedModule],
useFactory: async (configService: ConfigService) => ({
uri: configService.mongoDBName(),
useNewUrlParser: true,
useFindAndModify: false,
}),
inject: [ConfigService],
}),
UserDocumentsModule,
],
providers: [AppGateway],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): MiddlewareConsumer | void {
consumer.apply(contextMiddleware).forRoutes('*');
}
}
UPDATE
I think there is something wrong with the mongoose imports in the schema file. It says "could not find declaration for module 'mongoose'".
I tried removing and reinstalling mongoose and it's types. But now it shows new error.
I tried solutions mentioned in this post:
Node.js heap out of memory
But this also didn't work for me.
I'm using Mac-M1 with 8GB config.
UPDATE
The issue has been resolved now. The project is running on node v10.24.1 and I was using node v16.6.2.
After downgrading node version using NVM, this issue is gone.
You'll have to pull SharedModule import off MongooseModule.
Try this:
#Module({
imports: [
MongooseModule.forRootAsync({
useFactory: async (configService: ConfigService) => ({
uri: configService.mongoDBName(),
useNewUrlParser: true,
useFindAndModify: false,
}),
inject: [ConfigService],
}),
UserDocumentsModule,
SharedModule
],
providers: [AppGateway],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): MiddlewareConsumer | void {
consumer.apply(contextMiddleware).forRoutes('*');
}
}
It was because I was using a wrong version of node. The project was built on node v10.24.1 and I was using node v16.6.2.
After downgrading node version using NVM, I was able to fix this issue.

I cannot navigate to the dashboard page after logging in keycloak in angular

I get the following error
I added the codes as follows. Keycloak login screen appears. Cannot be redirect after login.
const keycloak_config = config.keycloak;
this.keycloakAuth = Keycloak(keycloak_config);
this.keycloakAuth.redirectUri = environment.baseUrl + '/dashboard' ;
this.keycloakAuth.init({onLoad: 'login-required',
checkLoginIframe: false})
.success(() => {
resolve();
})
.error(() => {
reject();
});
One of the information in the environment file;
baseUrl: 'http://localhost:4200'
code block in app-routing.module.ts. I done useHash : false. Because if useHash : true, page is not open. I get error so;
Error: Cannot match any routes. URL Segment: 'state' Error: Cannot match any routes. URL Segment: 'state' at Anonymous function (http://localhost:4200/vendor.js:82718:17) at CatchSubscriber.prototype.error
const routes: Routes = [
{
path: '',
component: ContentLayoutComponent,
children: CONTENT_ROUTES,
canActivate: [AuthGuard]
},
{
path: 'login',
component: AuthLayoutComponent
}
];
#NgModule({
imports: [RouterModule.forRoot(routes, {useHash: false, scrollPositionRestoration: 'enabled'})],
exports: [RouterModule]
})
export class AppRoutingModule { }

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 tab app throws error on new tab add

I am trying to add tabs in my exiting Ionic app:
directory structure:
- src/pages/admin/dashboard
- src/pages/admin/tabs
- ..../tabs/ tabs.module.ts , tabs.page.html , tabes.page.ts , tabs.router.module.ts
tabs.module.ts code:
import { DashboardPage } from '../dashboard/dashboard.page';
#NgModule({
imports: [
IonicModule,
CommonModule,
FormsModule,
TabsPageRoutingModule,
DashboardPage
],
declarations: [TabsPage]
})
export class TabsPageModule {}
tabs.router.module.ts code:
const routes: Routes = [
{
path: 'tabs',
component: TabsPage,
children: [
{
path: 'dashboard',
outlet: 'dashboard',
loadChildren: '../dashboard/dashboard.module#DashboardPageModule'
}
]
}
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class TabsPageRoutingModule {}
Tried all sources googles its changes as per the error message
but still stuck with below error message:
core.js:12501 ERROR Error: Uncaught (in promise): Error: Unexpected directive 'DashboardPage' imported by the module 'TabsPageModule'. Please add a #NgModule annotation.
Error: Unexpected directive 'DashboardPage' imported by the module 'TabsPageModule'. Please add a #NgModule annotation.
app environment ionic 4
Thanks for any help or hint
Your problem is in your error code:
Unexpected directive 'DashboardPage' imported by the module 'TabsPageModule'.
In tabs.module.ts you need to import the PageModule instead of the page itself.
So change DashboardPage to DashboardPageModule.

Getting Angular2 error 'No provider for Router! (RouterOutlet -> Router)'

I use Angular2 alpha39 and Babel to transpile the ES6 JS file. I'm not using typescript.
I created a component which displays correctly. I added a router-outlet to the template. When I run the app, I get the error message:
No provider for Router! (RouterOutlet -> Router)
The call stack is:
Here is the snippet of code:
template:
.... // Removed for brevity
<div class="contenttext">
<router-outlet></router-outlet>
</div>
.... // Removed for brevity
Component file:
import { Component, View, bootstrap, OnInit } from 'angular2/angular2';
import { RouteConfig, RouterOutlet, RouterLink } from 'angular2/router';
import 'reflect-metadata';
import 'winjs';
#Component({
selector: 'dashboard-app'
})
#View({
templateUrl: '../js/dashboard.html',
directives: [ ContentComponent, FamiliesComponent, RouterOutlet, RouterLink ]
})
#RouteConfig([
{ path: '/employees', component: EmployeesComponent, as: 'employees'}
])
class DashboardAppComponent implements OnInit {
constructor() {
}
onInit() {
WinJS.UI.processAll().done(function() {
var splitView = document.querySelector(".splitView").winControl;
new WinJS.UI._WinKeyboard(splitView.paneElement);
})
}
}
bootstrap(DashboardAppComponent);
you have to use:
ROUTER_BINDINGS in your bootstrap.
in your index.html.
if possible use state i.e as "employees" in capitalize i.r as "Employees". (in alpha 42 i have solve one problem this way).
i hope this will surely help you.
--UPDATE--
after the relese of alpha41:
ROUTER_BINDINGS has been changed with ROUTER_PROVIDERS .
Router Aliases should be in the camel case manner.
for the Router-outler and router-link you just have to import ROUTER_DIRECTIVES in your directives property in the component annotation.
Router-link expects the value to be an array of route names. for more info. refer here .
for more info regarding Routing you may refer to this tutorial here .
---Update2---
Now ( as of alpha-49) router is exported as ng.router.
(According to alpha-47 all life cycle hooks renamed as.)
onActivate, onReuse, onDeactivate, canReuse, canDeactivate
To :--
routerOnActivate,routerOnReuse,routerOnDeactivate,routerCanReuse,routerCanDeactivate
---Update3---
router-link is changed to routerLink
and routeconfig property changed to:
{path: '/abc', component: ABC, as: 'abc'}
to:
{path: '/xyz' , component: XYZ, name: 'xyz'}
--Update 4 --
UPDATE TO ANGULAR2 RC
There are alot of changes has been made in routing in angular2 after RC some of them points i am going to mention here may help someone :-
angular2/router has been changed with #angular/router
(also you can use old functionality of routing using import of #angular/router-deprecated but as of now we have to use #angular/router).
#RouteConfig has been changed with #Routes .
for example :-
#Routes([
{path: '/crisis-center', component: CrisisListComponent},
{path: '/heroes', component: HeroListComponent}
])
2.0.0-alpha.36 (2015-08-31)
routerInjectables was renamed to ROUTER_BINDINGS
2.0.0-alpha.41 (2015-10-13)
ROUTER_BINDINGS was renamed to ROUTER_PROVIDERS
USE ROUTER_PROVIDERS
ROUTER_PROVIDERS is used to simplify bootstrapping the router.
It includes:
RouterRegistry - the collection of registered routes
LocationStrategy = PathLocationStrategy - match by path
ROUTER_PROVIDERS provides 'sane' defaults and should be used unless you need to need a different route LocationStrategy.
Change:
bootstrap(DashboardAppComponent);
To:
bootstrap(DashboardAppComponent, [
ROUTER_PROVIDERS
]);
Sources:
angular/commit/ccfadb9
angular/pr#4654
2.0.0-alpha.38 (2015-10-03)
Route aliases need to be CamelCase (technically PascalCase)
Note: this was mentioned already in Pardeep's answer under #3
If you want to include a link to a route in your template via router-link you have to make sure the alias (ie the name property) of the route is PascalCase.
If you use plan to use router-link modify the route to:
{ path: '/employees', component: EmployeesComponent, name: 'Employees'}
Then you can add the link in your template with:
<a [router-link]="['/Employees']">Employees Link</a>
RouterLink dynamically inserts a href that matches the route path.
Note: Reading the issue/pr it appears this change was made to prevent users from confusing the <route-link> binding with the route url
Sources:
https://groups.google.com/d/msg/angular/IF3_UCJt340/6AgSF76XAwAJ
angular/issues#4318
angular/pr#4643
Tip:
If you want to simplify your view directives use ROUTER_DIRECTIVES
It includes:
RouterLink
RouterOutlet
Update:
In the near future, RouterOutlet/<router-outlet> will be renamed to RouterViewport/<router-viewport>
Source:
angular/issues#4679
Update 2:
The RouteConfig property as has been renamed to name
Source:
angular/commit/7d83959
Answer on Dec 23rd 2016 (Angular v2.4.1, Router v3.4.1 - should work for any NG v2.x.x + Router v3.x.x)
I just migrated three of our apps from the Webpack Starter Seed to Angular CLI (v1.0.0-beta.24) and hit this issue.
Only a tiny fraction of what's on the NG 2 massive router doc page is required:
An app-routing.module.ts file (typically in src/app/ folder) looking like this sample:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
const appRoutes: Routes = [
{ path: '', component: YourHomePageComponent },
{ path: 'next-page', component: NextComponent }
];
#NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule {}
Import AppRoutingModule into your main module (typically src/app/app.module.ts):
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule // <--- The import you need to add
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Ensure you have <router-outlet></router-outlet> somewhere in your main html (often src/app/app.component.html) as this is where router content is injected.
Make sure you have router defined and declared in AppModule.
Example (look everywhere where routing is mentioned, ignore the rest):
app.routing.ts
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HeroesComponent } from './heroes.component';
import {DashboardComponent} from './dashboard.component';
import {HeroDetailComponent} from './hero-detail.component';
const appRoutes: Routes = [
{
path: 'heroes',
component: HeroesComponent
},
{
path: 'dashboard',
component: DashboardComponent
},
{
path: '',
redirectTo: '/dashboard',
pathMatch: 'full'
},
{
path: 'detail/:id',
component: HeroDetailComponent
},
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
and app.module.ts:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
// Imports for loading & configuring the in-memory web api
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard.component';
import { HeroesComponent } from './heroes.component';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroService } from './hero.service';
import { routing } from './app.routing';
import './rxjs-extensions';
import {HeroSearchComponent} from './hero-search.component';
#NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
routing
],
declarations: [
AppComponent,
DashboardComponent,
HeroDetailComponent,
HeroesComponent,
HeroSearchComponent
],
providers: [
HeroService,
],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
This can save someone an hour:
You get this error if you don't even use routing (for example temporary, maybe you don't import routing config and router-outlet is commented out) BUT you are using Router or ActivatedRoute in some component constructor via dependency injection, like this:
#Component({...}})
export class SomeComponent {
constructor(private _router: Router, private _route: ActivatedRoute) {
//may be you are not using _route/_route at the moment at all!
}
...
}
You cant user Dependency Injection for Router if you dont define any routs!
To define route user something similar to following codes:
const loginRoutes: Routes = [
{path: 'foo/bar/baz', component: 'MyRootComponent'}
];
#NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
JsonpModule,
RouterModule.forRoot(loginRoutes)
],
providers: [],
declarations: [
MyLoginComponent
],
bootstrap: [
MyLoginComponent
]
})
export class MyLoginModule
{
}