Angular route with 2 parameters not working - javascript

I've got this routing file:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomepageComponent } from './app/homepage/homepage.component';
import { SearchpageComponent } from './app/searchpage/searchpage.component';
import { EventPageComponent } from './app/eventpage/eventpage.component';
const routes: Routes = [
{
path: '',
component: HomepageComponent
},
{
path: 'search',
component: SearchpageComponent
},
{
path: 'event/:name/:id',
component: EventPageComponent
},
];
#NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [RouterModule]
})
export class AppRoutingModule {
}
Whenever I try to navigate to an URL like http://localhost:4200/event/asa/123, it won't load the EventPageComponent (blank page) and Chrome gives me the following error in console:
Failed to load resource: the server responded with a status of 404 (Not Found) (http://localhost:4200/event/asa/inline.bundle.js)
It does that for every bundle.
Am I missing something?

It looks like your script reference in index.html is incorrect. It appears to be pointing at inline.bundle.js (relative to the current path) when it should be pointing at /inline.bundle.js (absolute). That's my best guess given your problem, I see nothing wrong with the Angular code (nor could anything in Angular produce this error).
If you're using something like webpack for bundling they no doubt have a solution for this.

Related

Angular SSR app fail to render homepage from url while server is running

I have an Angular SSR app that is not able to render the homepage via localhost:4000 while the backend node server is running.
So if I go to localhost:4000 it will start loading but never display anything nor finished loading. However, if I go to another page like 404 where I have a button to take me to the home page it does load it. Additionally, if I turn off the backend server it does load the homepage.
The app routes are handled like this:
//app-routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { GuardDashboardGuard } from './guard-dashboard.guard';
import { KYCGuard } from './guard-kyc.guard';
// More imports for other paths
const routes: Routes = [
{
path: 'profile-update',
canActivate: [GuardDashboardGuard, KYCGuard],
loadChildren: () =>
import('./pages/profile-update/profile-update.module').then((m) => m.ProfileUpdatePageModule),
},
// More paths with the same structure
{
path: '',
loadChildren: () => import('./pages/home/home.module').then((m) => m.HomePageModule),
},
{
path: 'faqs',
loadChildren: () => import('./pages/faq/faq.module').then((m) => m.FaqPageModule),
},
{
path: '',
redirectTo: '/',
pathMatch: 'full',
},
{ path: '**', redirectTo: '404' },
];
#NgModule({
imports: [
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled',
scrollOffset: [0, 0],
anchorScrolling: 'enabled',
relativeLinkResolution: 'legacy',
initialNavigation: 'enabledBlocking',
}),
],
exports: [RouterModule],
})
export class AppRoutingModule { }
I have tried fully deleting path: '', and the app redirected localhost:4000 to profile-update. Even if i delete profile-update I am still redirected to a Update Profile page.
Home page directory tree looks like:
.
├── home-routing.module.ts
├── home.module.ts
├── home.page.html
└── home.page.ts
// home-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomePage } from './home.page';
const routes: Routes = [
{
path: '',
component: HomePage,
},
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class HomePageRoutingModule {}
I am not sure what the cause of this error is or what code is relevant so I don't know what other code should be included in my question.
I also get a network error of crbug/1173575, non-JS module files deprecated.
and have found this Crbug/1173575, non-JS module files deprecated. chromewebdata/(index)꞉5305:9:5551 which was not very helpful to solve thebug.

Why Angular always redirecting to main page?

Always I trying to GET '/' it shows static-root-component (component of my main page),
but when it is '/welcome' page immediately redirecting to '/' and also loading static-root-component instead of welcome-component
Initially I wanted to redirect users to welcome page if they aren't authorized, but login status only can be checked within JavaScript. After JS got info about login status it decides to redirect using location.replace("/welcome"), but... Angular again goes to '/'
"Funny" fact: there isn't any routing problems during debug with ng serve but it always happens with ng build
I don't know what's gone wrong and there is app.module.ts:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { StaticRootComponent } from './static-root/static-root.component';
import { WelcomeComponent } from './welcome/welcome.component';
import { HttpClientModule } from '#angular/common/http';
import { HttpService } from './http.service';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
const appRoute: Routes = [
{ path: '', component: StaticRootComponent, pathMatch: 'full' },
{ path: 'welcome', component: WelcomeComponent }
];
#NgModule({
declarations: [
AppComponent,
StaticRootComponent,
WelcomeComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
RouterModule.forRoot(appRoute),
HttpClientModule
],
providers: [HttpService],
bootstrap: [AppComponent]
})
export class AppModule { }
I can drop any other Angular file if needed
In your code, change like below
const appRoute: Routes = [
{ path: '', component: StaticRootComponent },
{ path: 'welcome', component: WelcomeComponent },
{ path: '**', redirectTo: '' }
];
In the component file, inject this like below
import { Router } from '#angular/router';
constructor(
private router: Router
) {}
When you want do navigation use the below code instead of location.replace("/welcome")
this.router.navigate(['/welcome']);
Check the Module you trying to instantiate in the constructor of the Component linked to the Routing Path you are trying to access
In this case:
Our Component: example.component.ts
Our Module: HttpClientModule that contains HttpClient
Our Routing Path: "/example"
and make sure that Module is already existing in the app.module.ts , here is an example:
example.component.ts
import {HttpClient} from '#angular/common/http'; //child of HttpClientModule
#Component({selector: 'app-example',templateUrl: './example.component.html', styleUrls: ['./example.component.css']})
export class ExampleComponent{
constructor(private httpClient: HttpClient) { }
}
now let's see both examples of app module with and without the Module import and see the difference
app.module.ts
Without including HttpClientModule in imports array
import { AppComponent } from './app.component';
#NgModule({
declarations: [...],
imports: [BrowserModule,...],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
In this case loading the "/example" path will redirect you to the main page path which is usually "/" and that's because example.component.ts is using HttpClient (child of HttpClientModule) but not finding it in app.module.ts .
app.module.ts
Including HttpClientModule in imports array
import { AppComponent } from './app.component';
import { HttpClientModule} from '#angular/common/http'; //Import that module you willing to use
#NgModule({
declarations: [...],
imports: [BrowserModule,HttpClientModule,...], //add the module we currently using
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
In this case loading the "/example" path will work properly since we added the required module in app.module.ts.
If that's your case that would definitely fix your problem unless you have something else forcing the redirection to home page "index.html" or any other path, else if that didn't fix your problem read the following notes:
Make sure to check there are no redirections in the app-routing.module.ts routes array like this
const routes: Routes = [
{path: 'example', component: ExampleComponent},
{ path: '/example', redirectTo: '' }
];
it should only be like so
const routes: Routes = [
{path: 'example', component: ExampleComponent}
];
Also make sure there is no routing behaviour causing the redirection like #angular/router through something like this.router.navigate(['/'])
PS: SAME ISSUE COULD IMPLY IF YOU USING A SERVICE THAT'S USING A MODULE WHICH IS NOT ADDED TO MODULE IMPORTS IN app.module.ts
My project based on MEAN (Mongo, Express, Angular and NODEJS)... The last was a source of problem
#Shakthifuture, you said you want to see full code and I started answering:
"What you wanna to see else? My data and server files doesn't affec..."
and I've starting think "what if affect?": routing in whole of project works by Angular, but all new connection to the site pass NodeJS and Express, so I forgot about 404 case...
THE PROBLEM:
In server script file index.js of project's root folder a long time ago I've added code about what to do if entered path not found:
app.use(function (req, res, next) {
res.redirect('/');
// IF 404 NOT FOUND
});
and above of it something like:
app.get('/', function (req, res) {
res.sendFile(`${__dirname}/angular/index.html`)
});
// send index if path is '/'
but nothing for '/welcome', that's why redirecting happens
THE SOLUTION:
let's add the '/welcome' handler:
app.get('/welcome', function (req, res) {
res.sendFile(`${__dirname}/angular/index.html`)
});
(again index.html due to SPA)

Angular routing confusion/strange behavior

I have a base route with three sibling routes. The parent route routes to my task-list.component.ts which contains a navbar and router outlet.
I would like to have a route param on the base route where I can add an optional token
so when I navigate to http://localhost:4200 token should be undefined.
when I navigate to http://localhost:4200/123 token should be 123 in the activated route params
I have the below route config but i'm encountering confusing/strange behaviour.
When I navigate to http://localhost:4200 I get to my base taskList.component as expected.
When I try navigate to http://localhost:4200/123 I get a 404 not found? The expected bahaviour is that this should have navigated to taskList.component and added 123 to the activated route params...
even more strange when I click the deleted link in my navbar it navigates to the parent component app.component again only then I get "deleted" as the value in the activated route params...
Even more strange: when I navigate to http://localhost:4200 using my browser it doesn't set deleted as token instead I get a 404 not found again...
Any idea how I can achieve the above/what my issue might be?
my route module code:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import { TaskListComponent } from './task/task-list/task-list.component';
import { CompletedTasksComponent } from './task/completed-tasks/completed-tasks.component';
import { DeletedTasksComponent } from './task/deleted-tasks/deleted-tasks.component';
const routes: Routes = [
{ path: '', component: TaskListComponent, pathMatch: 'full' },
{ path: 'completed', component: CompletedTasksComponent },
{ path: 'deleted', component: DeletedTasksComponent },
{ path: ':token', component: TaskListComponent },
{ path: ':token/completed', component: CompletedTasksComponent },
{ path: ':token/deleted', component: DeletedTasksComponent }
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.component.html:
<nav mat-tab-nav-bar>
<a mat-tab-link
*ngFor="let link of links"
[routerLink]="navigate(link)"
(click)="activeLink = link"
[active]="activeLink == link">{{link}}</a>
</nav>
<router-outlet></router-outlet>
app.component.ts navigate method
navigate(link) {
switch(link) {
case 'Task List':
return `${this.token}`;
case 'Completed Tasks':
return `${this.token}/completed`;
case 'Deleted Tasks':
return `${this.token}/deleted`;
}
}
Old answer: You have some issues in your routes. you can fix it like :
RouterModule.forRoot([
{ path: "", component: TaskListComponent, pathMatch: "full" },
{ path: "deleted", component: DeletedTasksComponent },
{ path: ":id", component: TaskListComponent },
{ path: ":id/completed", component: CompletedTasksComponent },
{ path: ":id/deleted", component: DeletedTasksComponent }
])
Run It On Stackblitz
Update :
based on your edit and comments, now in app navigation works but you get 404 when you refresh the page (even in development environment). so try this: https://stackoverflow.com/a/35285068/4718434 . (Also on production, you should configure your server to return angular html file on every path.)

Not able to import IonicModule from path

I am fairly new to Angular and typescript but I have an Angular 6 project using Ionic 3 elements.
I am trying to import a library that is saved locally from the cdn from path ../lib/ionic.bundle.js into my project but I get template parse errors which indicates the module is not imported for that path.
Error: Template parse errors:
'ion-card-header' is not a known element:
1. If 'ion-card-header' is an Angular component, then verify that it is part of this module.
2. If 'ion-card-header' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message. ("
<ion-card>
import { IonicApp, IonicModule } from '../lib/ionic.bundle.js';
const routes: Routes = [
{
path: 'create',
component: CreateComponent
},
{
path: 'edit/:id',
component: EditComponent
},
{
path: 'index',
component: IndexComponent
}
];
#NgModule({
declarations: [
CreateComponent,
IndexComponent,
EditComponent,
],
imports: [
IonicModule.forRoot(routes)
],
providers: [ ...]
})
export class AppModule { }
I am sure the file exists at that path but not being imported from some reason.
Is there a different way of importing the IonicModule?
You should try importing it from node_modules instead.
In command line in your project dir:
$ npm i ionic
After its installed ionic, then try importing from ionic-angular:
import { IonicModule } from 'ionic-angular'

Routing error with angular 2 and IIS [duplicate]

I'm trying to create an application with hash location strategy, but it does not add the hash to the url. For instance when I click on a button associated with { path: '/polls', name: 'Polls', component: PollsComponent } it loads the page with this url : localhost:3000/polls.
What do I have to change to get the hash location strategy?
Why do I have to set the default base url if I want to use hash location strategy?
This is the routing in the app.component.ts where all the routing is defined:
import {Component} from 'angular2/core'
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import 'rxjs/Rx'; // load the full rxjs
import {ROUTER_PROVIDERS, RouteConfig , ROUTER_DIRECTIVES} from 'angular2/router';
import { ResultsComponent } from './results/results.component'
import { VotingCardsComponent } from './votingcards/votingcards.component'
import { DashBoardComponent } from './dash/dash.component'
import { PollsComponent } from './pollslist/pollslist.component'
#Component({
selector: 'my-app',
templateUrl: 'app/app.component.html',
directives: [ROUTER_DIRECTIVES, ResultsComponent, VotingCardsComponent, DashBoardComponent],
providers: [HTTP_PROVIDERS,
ROUTER_PROVIDERS]
})
#RouteConfig([
{ path: '/vote', name: 'VotePage', component: VotingCardsComponent },
{ path: '/votepoll/:id', name: 'VotePoll', component: VotingCardsComponent },
{ path: '/results', name: 'Results', component: ResultsComponent },
{ path: '/polls', name: 'Polls', component: PollsComponent },
{ path: '/', name: 'DashBoard', component: DashBoardComponent, useAsDefault: true }
])
export class AppComponent { }
And this is my main.ts where I configure the base url:
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './app.component';
//this is to avoid the href empty issue
import {provide} from 'angular2/core';
import {APP_BASE_HREF, ROUTER_PROVIDERS} from 'angular2/router';
bootstrap(AppComponent, [
//this is to avoid the href empty issue
ROUTER_PROVIDERS,
provide(LocationStrategy, { useClass: HashLocationStrategy }),
provide(APP_BASE_HREF, { useValue: '/' })
]);
You can use the option "useHash" in RouterModule.forRoot().
RouterModule.forRoot(appRoutes, {useHash: true});
https://discuss.atom.io/t/angular-2-routes-breaking-on-electron-app-refresh/28370/4
ROUTER_PROVIDERS should not be added to child components,
only to
providers: [ROUTER_PROVIDERS]
or alternatively only to
bootstrap(AppComponent, [ROUTER_PROVIDERS]);
HTTP_PROVIDERS are in my opinion also a better fit for root component or bootstrap() but it doesn't break anything to add them somewhere else.
(See also Routing error with angular 2 and IIS)
Everything worked fine with the sample code OP posted as with what is in the accepted answer. But as a minor note, the format required to changing the Hash Location Strategy in the bootstrap file as of RC.4 goes like this:
{ provide: LocationStrategy, useClass: HashLocationStrategy },
It is recommended to use the HTML 5 style (PathLocationStrategy) as location strategy in Angular
Because
It produces the clean and SEO Friendly URLs that are easier for users
to understand and remember.
You can take advantage of the server-side rendering, which will make
our application load faster, by rendering the pages in the server
first before delivering it the client.
Use Hashlocationstrtegy only if you have to support the older
browsers.
Click Here for More info

Categories