Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2.0 deep-linking does not work. Same from the address bar

Everything works OK when I build and navigate links in the app but typing in the address bar does not! Eventually I want to be able to send a link to a specific app page/path via email and I am not sure how to accomplish that.

I have followed the angular router guide documentation. Correctly I think...

I'm using NodeJS (with express) and in the server I have redirected all traffic to the app root.

app.get("*", function(req, res) {
    console.error("in get *")
    res.redirect("/");
});

In my index.html I have set base

<base href="/">

I have my client routs/paths set as follows

const appRoutes: Routes = [
  { path: 'vendor/registration', component: VendorRegistrationComponent },
  { path: 'vendors', component: VendorListComponent },
  { path: '',  redirectTo: 'vendor/registration', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }    
];

If I type http://localhost:8080/vendors in the browser address bar I get to http://localhost:8080/vendor/registration which kind of makes sense because that's where the server tells the browser to redirect to.

How then should I deep link to my app?

Edit. The Angular tutorial - "TOUR OF HEROES" - also exhibits the same behavior. i.e. entering urls in the browser's address bar directly does not work. The app shows a "loading..." text and does not route to the controller.

like image 318
nsof Avatar asked Feb 21 '17 07:02

nsof


1 Answers

Generally you would not need to redirect on the server since all of your routing is handled by the angular router on the client.

Instead make your catch-all express route simply always serve your index.html for all requested urls. When the client app bootstraps, angular will take care of routing to the appropriate component based on the requested url. Make sure to keep your <base href="/"> tag so that angular can be aware of what part of the url is routed.

const path = require('path');

app.get("*", function(req, res) {
    res.sendFile(path.join(__dirname, '/path/to/your/index.html'));
});
like image 60
jgranstrom Avatar answered Oct 20 '22 17:10

jgranstrom