What is the process for modifying href generation in UI-Router for Angular 2?

I am currently working on implementing subdomain support for UI-Router. Consider the following routes with a custom attribute 'domain':

{ name: 'mainhome', url: '/', domain: 'example.com', component: 'MainSiteComponent' },
{ name: 'bloghome', url: '/', domain: 'me.example.com',
component: 'BlogComponent' },

PLEASE NOTE: both routes share the same route URL

I am aiming to modify the href generation by the uiSref directive, taking into account the current domain AND the custom domain property.

The active route should be identified as either "mainhome" or "bloghome" depending on the current domain.

When accessing http://example.com/:

<a uiSref="mainhome"> transforms into <a href="/">

<a uiSref="bloghome"> turns into

<a href="http://me.example.com/">

Upon visiting :

<a uiSref="mainhome"> changes to

<a href="http://example.com/">

<a uiSref="bloghome"> is converted to <a href="/">

Your assistance with this matter would be greatly appreciated!

Answer №1

To manipulate the path part of the URL, ui-router is the tool to use as it focuses on path rather than hostname. In cases where you need to deal with different domains, it might be best to consider building two separate apps.

One way to control the transition between states is by using a transition hook. This hook allows you to intercept and handle the next transition, making it possible to redirect to a different domain if needed.

If you're looking for a quick example, check out this plunker sample based on the ui-router hello-world demo.

Let's start by defining the states:

const states = [
    { name: 'mainhome', url: '/', host: 'example.com', component: 'MainSiteComponent' },
    { name: 'bloghome', url: '/', host: 'me.example.com', component: 'BlogComponent' },
]

We can then create an onStart transition hook that will run before any state transition, checking if the next state has a different host compared to the current one.

function uiRouterConfigFn(router: UIRouter, injector: Injector) {
    router.transitionService.onStart({to: "*"}, function($transition) {
         const nextState = $transition.to();
         const host = window.location.host;
         if (nextState && nextState.host && nextState.host !== host) {
             window.location = `${window.location.protocol}://${nextState.host}/${nextState.url}`;
        }
    });
}

Lastly, utilize the config method to apply our configuration function:

@NgModule({
    imports: [ 
        ...,
        UIRouterModule.forRoot({ states: states, config: uiRouterConfigFn })
   ],
   ...
})
class RootAppModule {}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Cannot access Angular 5 Title service at this time

When attempting to change the page title using BrowserModule, I encountered an issue. I added the BrowserModule and Title in the application module as shown here: https://angular.io/guide/set-document-title However, in a child module where I tried to add ...

Struggling to share information between components using RxJS Subject or a shared service?

I've been attempting to transfer data between components using a Subject and a shared service, but I'm encountering issues with it not functioning as expected. It's worth mentioning that I included the service at the module level rather tha ...

Clear out the existing elements in the array and replace them with fresh values

Within my Progressive Web App, I am utilizing HTTP requests to populate flip cards with responses. The content of the requests relies on the selected values. An issue arises when I choose an item from the dropdown menu. It triggers a request and displays ...

Erase Typescript Service

To remove a PostOffice from the array based on its ID, you can use a checkbox to select the desired element and then utilize its ID for the delete function. Here is an example: let postOffices = [ {postOfficeID: 15, postCode: '3006&ap ...

What is the best way to add a 'Drawer' component into the 'AppBar' using React MUI within the Next.js framework?

My goal is to create an App bar with a 'hamburger' icon on the left that, when clicked, will display a Sidenav (drawer). I am working with React Material and Next.js (App router) and need to have the app bar and drawer as separate components, hea ...

Is there a way to adjust the width of a table cell in Material UI using React?

I encountered a problem where I am attempting to adjust the width of a table cell, specifically in Typescript. However, I am only able to choose between medium and small sizes for TableCellProps. Is there a workaround for this issue? I am looking to expand ...

An effective way to extract targeted information from an array of objects using Typescript

I'm having trouble extracting the IDs from the selected items in my PrimeNG DataTable. Despite searching on Google, I couldn't find much information about the error I'm encountering... ERROR in C:/Users/*****/Documents/Octopus/Octopus 2.0/s ...

Unable to link with 'NgModel' as it is not recognized as a valid property of 'ion-input'

I'm experiencing some difficulty with the following error message: Error: Uncaught (in promise): Error: Template parse errors: Can't bind to 'NgModel' since it isn't a known property of 'ion-input'. 1. If 'ion-input ...

Efficiently transforming a nested object array into a single dynamic array

// I have a collection of various objects _id: "5e5d00337c5e6a0444d00304" orderID: 10355 orderDate: "2020-03-02" user: _id: "5e2e9699a648c53154f41025" name: "xyz1" email: "<a href="/cdn-cgi/l/email-protection" class="_ ...

Angular fails to include the values of request headers in its requests

Using Django REST framework for the backend, I am attempting to authenticate requests in Angular by including a token in the request headers. However, Angular does not seem to be sending any header values. Despite trying various methods to add headers to ...

Launching an Angular application from the local server

I have successfully deployed an Angular frontend on a server. It is functioning well, with three scripts: /runtime.0fad6a04e0afb2fa.js /polyfills.24f3ec2108a8e0ab.js /main.a9b28b9970fe807a.js My goal is to start this application in Firefox without ...

A specialized HTTP interceptor designed for individual APIs

Hey there, I am currently working with 3 different APIs that require unique auth tokens for authentication. My goal is to set up 3 separate HTTP interceptors, one for each API. While I'm familiar with creating a generic httpInterceptor for the entire ...

Exploring Typescript: Enhancing the functionality of `export = Joi.Root`

I've noticed that the types for @hapi/joi appear to be outdated - some configuration parameters mentioned in the official documentation are missing from the types. To address this, I am attempting to enhance the existing types. node_modules/@types/ha ...

Having difficulty updating the value of a FieldArray with setFieldValue in Formik

Thank you for taking the time to read this. I am currently working on creating a form using Formik that involves nesting a FieldArray within another FieldArray. Oddly enough, setFieldValue seems to be functioning correctly as I can log the correct values ...

Stop unnecessary updating of state in a global context within a Functional Component to avoid re-rendering

I am currently working with a Context that is being provided to my entire application. Within this context, there is a state of arrays that store keys for filtering the data displayed on the app. I have implemented this dropdown selector, which is a tree s ...

Using the spread operator in the console.log function is successful, but encountering issues when attempting to assign or return it in a

Currently facing an issue with a spread operator that's really getting on my nerves. Despite searching extensively, I haven't found a solution yet. Whenever I utilize console.log(...val), it displays the data flawlessly without any errors. Howev ...

Switch up a button counter

Is there a way to make the like count increment and decrement with the same button click? Currently, the code I have only increments the like count. How can I modify it to also allow for decrements after increments? <button (click)="toggleLike()"> ...

`ngCustomTranslation` - automatically defaults to `English` if no other language is specified

Currently, I am utilizing ng2-translate for language translation. However, even after changing the language setting, the translation still defaults to en. Ideally, I want it to switch to fr, but my default language is not loading at all. Below is a snippet ...

Implementing dynamic image insertion on click using a knockout observable

I'm utilizing an API to retrieve images, and I need it to initially load 10 images. When a button is clicked, it should add another 10 images. This is how I set it up: Defining the observable for the image amount: public imageAmount: KnockoutObserva ...

Determining the appropriate scenarios for using declare module and declare namespace

Recently, I came across a repository where I was exploring the structure of TypeScript projects. One interesting thing I found was their typings file: /** * react-native-extensions.d.ts * * Copyright (c) Microsoft Corporation. All rights reserved. * Li ...