How to ignore a subroute in Angular?

Viewed 97

I have an Angular application running under a domain, and I have a different application running under the same domain on a subroute (/blog). If I try to open the subroute in a browser, it opens correctly. But if I open the main application first, and then I try to open the subroute, it redirects to the main application. It doesn't seem to reach the subroute application at all. The router of the main application is configured to catch the invalid subpages with the following route:

{ path: '**', redirectTo: '/' },

Is there a way to ignore the '/blog' route in the main application, but catch every other invalid route?

3 Answers

I had this same scenario about a year ago. Here is what I did:

Create a redirect provider

@NgModule({
    providers: [
        {
            provide: 'UrlRedirect',
            useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) =>
            {
                window.location.href = (route.data as any).externalUrl;
                // Angular might block reload because of same url, if does not you  do not need to reload specifically and delete this line
                window.location.reload();
            }
        }
    ]
})

Use the resolver

Now declare a route and provide the resolve with url as data to redirect

{
        path: 'blog',
        component: NotFoundComponent,
        resolve: {
            // Again, Injection token can be used here instead of plain string
            url: 'UrlRedirect'
        },
        data: {
            externalUrl: 'http://www.somedomain.com/blog'
        }
    }

PS: You can also use an Injection Token for this, but for this example I am just using a string.

Thanks for all the replies. I managed to find the issue with the service worker of the main application. The service worker was caching the assets of the main application. When I opened the subroute, the service worker tried to load it from the cache, leading back to the main application. I added the following data group to the service worker config (ngsw-config.json) to avoid caching the /blog subroute.

  "index": "/index.html",
  "assetGroups": [
    ...
  ],
  "dataGroups": [
    {
      "cacheConfig": {
        "maxAge": "0u",
        "maxSize": 0,
        "strategy": "freshness"
      },
      "name": "blog",
      "urls": ["/blog", "/blog/**"]
    }
  ]

To navigate a external url

  1. In .html use

    <a href="https://yourdominio/blog/...">...</a>
    
  2. In .ts you can inject the document and use

    constructor(...,@Inject(DOCUMENT) readonly document: Document) {}
    
    get window(): Window { return this.document.defaultView; }
    
    navigate(href:string)
    {
          this.window.open(href);
    }
    
Related