Retrieve the service variable in the routing file

How do I access the service variable in my routing file?

I created a UserService with a variable named user and I need to use that variable in my routing file.

Here is the approach I tried, but it didn't work:

In the routing file, I attempted:

const steps = this.userService.user.onboardingStatus;   //throws an error ---> *cannot find name userService*

const routes: Routes = [
   {
      path: 'welcome',
      component: WelcomeComponent,
   },
   {
    path: 'product-selection',
    component: ProductSelectionComponent,
    canActivate: [ClientRoutesGuard],
    data: {
      isStepAccessible: steps.['welcome'].status,   //will return true or false
    },
  },
]

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class ClientRoutingModule {
   constructor(public userService: UserService) {}
}

Thank you for your help!

Answer №1

To ensure that the user can only access the 'product-selection' route if the status of steps['welcome'] is true, you need to implement a guard for it. Here's an example:

export class ProductSelectionGuard implements CanActivate {
    constructor(private userService: UserService) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return this.userService.user.steps['welcome'].status;
    }
}

Then add your guard to the canActivate array for the specific route:

  // ... other routes
  {
    path: 'product-selection',
    component: ProductSelectionComponent,
    canActivate: [ClientRoutesGuard, ProductSelectionGuard],
    // data: {
    //  isStepAccessible: steps.['welcome'].status,   //will return true or false
    // },
  },

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

Calculating the total number of clicks on a button using PHP

I am attempting to track the total number of clicks on a button by individual users, rather than combining all members' clicks. Each user's clicks on the button should be logged separately. I am struggling to determine the best approach for this ...

Angular 14 now offers ngx-pinch-zoom for an enhanced zooming experience

Is it possible to add ngx-pinch-zoom to an Angular 14 project? I encountered a peer dependency conflict when trying to install pinch-zoom with --legacy-peer-deps, which worked in the project but failed in the ci/cd pipeline due to the conflict. I attempt ...

When intercepted, the HttpRequest is being canceled

Solution Needed for Request Cancellation Issue Encountering a problem with the usage of HttpInterceptor to include the Authorize header in all HTTP requests sent to AWS API Gateway. The issue arises as all these requests are getting cancelled when interce ...

Modify the event from creating a table on click to loading it on the page onload

Hey there, friends! I've been brainstorming and came up with an idea, but now I'm stuck trying to switch the code to onload(). I've tried numerous approaches, but none seem to be working for me. Below is the code I've been working wit ...

Tips for incorporating an outside model into vue.js with babylon js

Struggling with importing a gltf file into vue.js using babylon.js to create a 3D view on a webpage. The documentation online isn't very clear, and I've tried the following steps in my Hello.vue file: <div> <h1> Hello </h1> < ...

Ways to access the entire parent element, rather than just the individual child element, following the use of e.target

Looking to target the li element itself when clicked, rather than its child elements. The goal is to determine which specific option the user selects from a dropdown menu using event.target in jQuery. If the user chooses an li with a class of 1, set one gl ...

"Encountering Issues with Angular's Modules and EntryComponents during Lazy Loading

Upon lazy loading an Angular module, I encountered an issue when trying to open my DatesModal that resulted in the following error: No component factory found for DatesModal. Have you included it in @NgModule.entryComponents? The declaration and entryCom ...

Displaying two div elements horizontally using Material-UI

Can the styled utility from mui be used to align 2 divs side by side? The documentation examples don't seem to cover this specific scenario. While answers on this and this address it, they don't relate to mui / material ui. I attempted the fol ...

Babelify is having trouble transpiling JSX code within the node_modules directory

I have successfully set up Babelify to transpile jsx code to js, and I've created node_modules before, allowing me to link them without a specific file path, just the package name. However, when I add jsx code within my node_module code, babelify flag ...

Incorporating AngularFire2 in the latest Angular 11.0.5 framework

I have been attempting to utilize Firebase as a database for my angular application. Following the guidance provided in these instructions (located on the official developers Github page), I first installed npm install angularfire2 firebase --save in my p ...

Tips for utilizing the <base> element in HTML5 for selective anchor tags

I only have one base tag in the head section of my HTML document, and there are two anchor tags with different URLs as shown below: <!DOCTYPE html> <html lang="en"> <head> <base href="https://www.youtube.com"/> </head> &l ...

Creating JSON arrays with JavaScript and jQuery

User Information var Users=[{"Id":1,"FirstName":"John"},{"Id":2,"FirstName":"Emily"}] Call Information var CallInfo=[{"Id":1,"PercentageCalls":"22 %","TotalTime":"60:24 minutes","PercentageTime":"0 %","AvgTime":"0:22 minutes"},{"Id":2,"PercentageCa ...

Implement a feature to dynamically load data as the user scrolls up, similar to the

I am in the process of creating a messaging platform and I am looking to implement a functionality where chat history is displayed upon scrolling up, similar to Facebook's chat system. Can anyone offer assistance with this task? ...

Issue with Angular: no action taken when re-calling function and utilizing the

In one of my components, I am using route parameters to switch between different "tabs". Whenever I switch tabs, I call a function specific to that tab which is subscribed to the route parameters. Here is an example of one of those functions: getUserFeed( ...

Put the browser into offline mode using JavaScript

Currently, I am utilizing selenium for application testing purposes. Although I typically start my browser in the usual manner, there comes a point where I must transition to offline mode. I have come across various sources indicating that switching to off ...

What is the proper way to enhance properties?

In the process of developing a Vue3 app using Typescript, one of the components is designed to receive data through props. Initially, everything functioned smoothly with the basic setup: props: { when: String, data: Object }, However, I de ...

Unable to adjust dimensions with CSS width and height properties

I'm currently working on developing an online game with a login screen inspired by Paper.io. I have created the username input and play button, but there seems to be an issue with the width and height specified in the CSS file for the input field. Eve ...

Revolutionizing the way data is updated: Angular 2 and Node JS collaborate

In my Angular 2 application, I have incorporated a dynamic navbar that displays the count of unread messages for each user. Interestingly, when a person clicks on a specific message, it is correctly marked as read in the database. However, an issue arises ...

Identifying the specific promise that failed within a chain of .then statements

I am currently working on setting up a chain of promises with an error catch at the end within my node and express application. One issue I have encountered is that if any of the 'then' functions encounter an error, it can be difficult to trace b ...

Using spyOn to fake Observable responses - a step-by-step guide

My service is set up to request JSON data through HTTP: export class TodosService { constructor(private http: HttpClient) {} getTodos(): Observable<any> { return this.http.get<any>('https://jsonplaceholder.typicode.com/todos') ...