Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle deep links in Angular?

Tags:

angular

There has been a lot of questions about this. I've been browsing them for days. I tried everything, and neither worked. Yes, I've checked angular.io too, and that didn't work either. So please, can someone come up with the ultimate answer or point me to one which I've probably not seen yet?

Here is this URL, a deep link to an Angular app called whatever and its someroute route with a parameter.

http://somedomain.com/whatever/someroute/123456 

Of course it results in a 404 error. The web server has to be configured. My server runs nginx and I did this:

location / {      try_files $uri $uri/ /whatever/index.html; } 

Now it redirects every site's 404 error on this server to my Angular app, but that's a secondary issue. The problem is that the route still doesn't want to kick in. The default / route is invoked every time, and not /someroute/123456.

Instead of pointing to various tutorials which I've probably already seen and tried, can someone briefly explain what is the trivial point I missed?

like image 795
Tamás Polgár Avatar asked Jul 01 '17 19:07

Tamás Polgár


People also ask

What is deep linking in Angular?

Deep linking is the way to take user to a specific page without going anywhere else and transfer to that page. It also helps to index pages in search engines; it's good to have for a single load web site / application created using Angular. The default prefix is # when HTML 5 modes is not set.

How do you deep link a website to the app?

If you want to handle deep linking in both Android and iOS, it is recommended to use Dynamic Links. With Dynamic Links , you treat on all platforms such as Android, iOS and web in a similar way. It seamlessly transits users from your mobile website to the equivalent content within your app.


Video Answer


2 Answers

It sounds like you may be missing the <base href=""> tag. This tag tells the Angular router what the base URI is for your application. If this is not present then Angular assumes that the initial navigation URI (in your case, /whatever/someroute/123456) is the base URI and all subsequent routing will be performed relative to that URI.

Try including <base href="/whatever/"> in the <head> element of your index.html to direct the router accordingly.

You may also control the <base href=""> meta tag via ng build if you are using the Angular CLI:

ng build --base-href '/whatever/' 
like image 84
Mike Hill Avatar answered Sep 30 '22 11:09

Mike Hill


You can switch to the HashLocationStrategy, i.e.

RouterModule.forRoot(appRoutes, {useHash: true}); 

This results in all app urls being index.html, followed by "#" and then the routing information.

Since you're always going to index.html, regardless of the route, you won't get a 404 for any valid URL.

like image 36
GreyBeardedGeek Avatar answered Sep 30 '22 11:09

GreyBeardedGeek