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

How can you convert all nodes of a nested JSON tree into class instances in Angular 2 using Typescript?

I have a Leaf class that I want to use to convert all nodes in a JSON response into instances of Leaf. The structure of the JSON response is as follows: JSON Response { "name":"animal", "state":false, "children":[ { "name" ...

What is the proper way to access the current value of a computed property from within its own computation method?

Our goal is to activate a query when a string reaches a length of 3 characters or more, and keep it activated once triggered. Leveraging the Vue 2 Composition API, we have implemented a reactive object to manage the status of queries: import { computed, de ...

Tips for modifying the text color of a div that is being iterated through using ngFor

I am facing an issue with a div that is being looped using ngFor. What I want to achieve is when a user clicks on one of the divs in the loop, only that particular div should change its text color. If another div is clicked, it should change color while th ...

Best practices for extending the Array<T> in typescript

In a discussion on extending the Static String Class in Typescript, I came across an example showing how we can extend existing base classes in typescript by adding new methods. interface StringConstructor { isNullOrEmpty(str:string):boolean; } String. ...

NextJS applications can encounter issues with Jest's inability to parse SVG images

Upon running yarn test, an unexpected token error is encountered: Jest encountered an unexpected token This typically indicates that Jest is unable to parse the file being imported, suggesting it's not standard JavaScript. By default, Jest will use ...

Angular's mechanism for detecting changes in a callback function for updates

I have come across a puzzling scenario regarding a basic issue. The situation involves a simple component with a boolean property that is displayed in the template of the component. When I update this property within a callback function, the property is up ...

Embedding content within various ng-template elements

I'm currently working on developing a button component (app-button) that can utilize multiple templates based on the parent component using it. <div class="ds-u-margin-left--1 ds-u-float--left"> <ng-container *ngTemplateOutlet="icon">< ...

Unable to modify ui-view template from nested state

I'm trying to display the loginModal.html inside the loginModal view after the user enters the main.login state, but it's not working as expected. Why is that? html <div ui-view="loginModal"> </div> <div ui-view="content"> ...

Troubleshooting the ERR_CONNECTION_RESET issue when uploading large files on Angular 7 with Node JS and IIS, using pm2 for

Can you assist me? I am encountering a problem where the connection gets reset and an error message ERR_CONNECTION_RESET appears when trying to upload large files (150+MB) to the server. This issue only occurs when interacting with the public API, everythi ...

What is the reason `addEventListener` does not work with a class method?

Recently, I discovered that the listener passed to addEventListener can actually be an object with a handleEvent function instead of just a callback function (here). However, I encountered an issue when trying to use handleEvent as a class method: class F ...

Creating a String Array and linking it to an Input Field

I'm currently working on a code that involves mapping through an array of strings using observables. My objective is to display the value from this array inside an input field. However, despite being able to view the array in the console, I encountere ...

The Glyphicon is failing to display on the template

I recently set up bootstrap in my VS Code environment and linked it to the styles.css file with this code snippet: @import '~bootstrap/dist/css/bootstrap.css'; Upon further inspection of the package.json, I confirmed that "bootstrap": "^4.1.1" ...

How to dynamically load a component in Angular 2 using a string argument

I am currently developing an app that performs static analysis on components from an Angular application and then renders them within another Angular app. This app serves as a comprehensive style guide with detailed information on inputs and other key aspe ...

Learn how to dynamically chain where conditions in Firebase without prior knowledge of how many conditions will be added

Currently, I am working on a project using Angular and firebase. My goal is to develop a function that can take two arguments - a string and an object, then return an Observable containing filtered data based on the key-value pairs in the object for a spe ...

The configuration file tsconfig.json did not contain any input

After downloading angular2-highcharts through npm for my application, I encountered an error in the tsconfig.json file of the package while using Visual Studio Code: file: 'file:///c%3A/pdws-view-v2/node_modules/angular2-highcharts/tsconfig.json&apos ...

What strategies can be implemented to restrict certain users from accessing specific components by manually altering the URL in Angular 2?

I am currently using Angular 2 to create a data table for displaying information. I have implemented a click event that redirects users to '/viewOutgoing;id=data_id', with the id corresponding to the data's id in the table. However, I need t ...

Utilizing and transmitting contextual information to the tooltip component in ngx-bootstrap

I am currently working on integrating tooltips in ngx-bootstrap and trying to figure out how to pass data to the ng-template within the tooltip. The documentation mentions using [tooltipContext], but it doesn't seem to be functioning as expected. Belo ...

Issue encountered with Angular when making a post request, whereas there is no problem with J

I am attempting to send a post request containing information to a token Uri. This information should result in receiving an access token back from the token Uri once authorization is granted. I have successfully implemented this on a plain HTML page using ...

How to access the Parent ViewContainerRef within a projected child component in Angular 5

I have a unique application structure where the App component contains dynamically created components. The Parent component utilizes an <ng-content> element for projecting child components inside itself. App Component: @Component({ selector: &apo ...

How to set the default option in a select dropdown using Angular and Types

It's been a while since I last worked with Angular and now I'm tasked with working on an existing system. I introduced an NgModal dialog to send text messages, designed as shown here: https://i.sstatic.net/67U1M.png Below is the code snippet I ...