Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot load files when paste URL manually Angular 2 routing?

I make this routing config

@RouteConfig([
  {
    path:'/profile/:id',name:'Profile',component:ProfileComponent
  },
  // else
  {
    path: '/**',
    redirectTo: ['Home']
  }
])

and used this to navigate Profile with parameter {id:5}

<a [routerLink]="['Profile', {id:5}]" >Go </a>

i added to index.html head this base

<base href="/">

It successfully navigated to

http://localhost:3000/profile/1

and worked fine

but when i paste same URL manual in browser and hit enter it give me this error

enter image description here

Error happen because files are not loaded from root directory

http://localhost:3000

but browser trying to load them form relative URL directory

http://localhost:3000/profile/1

UPDATE: I am using angular 7 now, this kind of problem is fixed without need to add any thing

like image 618
Amr Ibrahim Avatar asked Sep 16 '16 17:09

Amr Ibrahim


People also ask

Can not match any routes angular?

This generally occurs when there is a mismatch in the routes specified, or a component which is not present in our routing configuration, or if there is the use of multiple routes in our angular application which is not properly configured.

How do you restrict a user to access a particular page using a direct URL in angular?

You can import router in the constructor of a guard. This router instance will have the current URL. ActivatedRouteSnapshot and RouterStateSnapshot in canActivate will contain the URL that the user is attempting to access. The below example prevents users from directly accessing a route from an outside page.

How does routerLink works?

RouterLinklink. When applied to an element in a template, makes that element a link that initiates navigation to a route. Navigation opens one or more routed components in one or more <router-outlet> locations on the page.


1 Answers

I solved that problem by adding # to my routes, for example http://localhost:3000/#/profile/1, you can try to do the same. Someone may have better fix for this problem though. Anyway, my solution is adding HashLocationStrategy to AppModule providers:

{ provide: LocationStrategy, useClass: HashLocationStrategy }

Of course, before that, you need to import LocationStrategy and HashLocationStrategy:

import { LocationStrategy, HashLocationStrategy } from '@angular/common';

If you are using RC4 or lower, you add this to your bootstrap method, for example:

bootstrap(
AppComponent,
    [
        { provide: LocationStrategy, useClass: HashLocationStrategy }
    ]);
like image 156
Stefan Svrkota Avatar answered Oct 02 '22 07:10

Stefan Svrkota