Devising and invoking Angular Service functionalities

Good day, I have implemented an "if" condition inside the ngOnInit method to handle routing issues in my manage-actives component. If a user is on the manage-actives URL and adds a "/" followed by any text, they will be redirected to the home page.

manage-actives-crud.components.ts

public ngOnInit(): void {
        this.loading = true;
        this.route.params.subscribe(params => {  
            console.log(params);         
            this.mode = params['mode'];
            if (this.mode !== 'create' && this.mode !== 'edit' && this.mode !== 'view') {
                this.router.navigate(['home']);
            }
            this.id = params['id'];
        });
        this.initData();
    }

To make this functionality reusable, I am planning to create a service. I have started working on it in the util.service file. Now, I need to figure out how to call this service from the manage-actives component instead of using the if condition directly.

util.service.ts

import { Router } from '@angular/router';
import { Injectable } from '@angular/core';
import { HttpParams } from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})

export class UtilService
{
    public mode: string;

    constructor(
        private router: Router
     ) { }

    public invalidUrl(url: any): void
    {
        if (this.mode !== 'create' && this.mode !== 'edit' && this.mode !== 'view') {
        void this.router.navigate(['home' + url])
        }    
    }
}

Answer №1

Implement a guard to control access to specific routes:

@Injectable({ providedIn: 'root' })
export class AccessGuard implements CanActivate {
  constructor(private router: Router, private route: ActivatedRoute){}

  canActivate(): Observable<boolean | UrlTree> {
     this.loading = true;
     this.route.params.subscribe(params => {  
         console.log(params);         
         this.mode = params['mode'];

         if (this.mode !== 'create' && 
             this.mode !== 'edit' && 
             this.mode !== 'view') {
             this.router.navigate(['home']);
             return false;
         }
 
         return true;
     });
  }
}

In the routing module file, apply the guard to specific routes:

import { AccessGuard } from './guards/access-guard'

const routes: Routes = [
  { 
    path: 'manages-access', 
    component: ManageAccessibleComponent, 
    canActivate: [AccessGuard] // Use arrays for multiple guards
  },
  {
    path: 'another-component-route',
    component: 'AnotherComponent',
    canActivate: [AccessGuard]
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)], 
  exports: [RouterModule]
})
export class AppRoutingModule {}

If AccessGuard returns true, the user can proceed to the route. If it returns false, the guard redirects the user to the home route.

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

Tips on refreshing asset information within a live Angular application

I am currently managing an Angular project on a web server. The server houses python scripts that run periodically to generate a .json file. This latest version of the .json file replaces the existing one in the assets folder of the project (dist/test/asse ...

The angular application fails to load the page properly and keeps refreshing itself

I'm currently working on an Angular app that searches for a Github user based on their username and then displays the list of repositories. When a user clicks on a repo name, it should show the open issues and contributors associated with that reposit ...

"An undefined message will be displayed in AngularJS if there is no content

When the two textboxes are left empty, you will see errors as 'undefined' displayed. These errors disappear once content is entered. The code I have written looks like this: Default.aspx <div ng-app="Welcomecontroller" ng-controller="FullNa ...

Prevent user input in Angular by disabling a field when it undergoes a

I recently started working with Angular and am facing a challenge in my project. I need to disable a field after it has been changed a certain number of times (3), but I'm struggling to figure out the logic for it. If anyone could provide me with guid ...

I encountered TS2300 error stating a duplicate identifier appeared once I transferred my code to Angular CLI

Currently undergoing the process of transitioning our code to Angular CLI for our hybrid app. The plan is to migrate the Angular part to CLI while the AngularJS portion continues to be handled by custom Webpack. It's worth noting that both parts (Angu ...

Troubleshooting TypeScript import problems within apollo-server-express, apollo-server, and apollo-cache-control

Currently, I am in the process of upgrading from "apollo-server": "^2.9.4" and "apollo-server-express": "^2.9.4 to version 2.12.0 in my Typescript project. However, while building the application, I encountered the following error: node_modules/apollo ...

Exploring the functionalities of Angular components

I have encountered an issue while testing my class that relies on a single dependency, which is a service. Despite trying various methods such as using stubs, I am still facing the problem of an undefined method. https://i.stack.imgur.com/A3by2.png Testin ...

Having trouble with passing parameters to the onclick event in an Angular directive

Check out the following Angular directive: angular.module("mySystem").directive("pageFooter", function () { return { restrict: "E", scope: { footerhref: '&' }, template: <button onclick="{{footerhref}}">{{fo ...

Utilizing the same code for multiple UI-Select components within an Angular application

Is there a way to efficiently reuse code when dealing with multiple ui-select elements in an Angular app, each connected to different remote APIs to populate options? After reading about AngularJS Wrapping a ui-select in a custom directive, I was inspired ...

The Angular material datepicker fails to organize items in a horizontal row

My web application features an Angular Material datepicker, however, I am facing an issue where not all elements are showing up in a row. The view is as follows: Datepicker To prevent any custom CSS from impacting the view, I have removed all customized ...

Incorrect errors are displayed by VS Code in ts-node shell scripts

I came across an interesting article discussing running a TypeScript file on the command line, and while it seems to be functioning properly, I am encountering invalid errors in VS Code: https://i.sstatic.net/eis3X.png As seen in the terminal (bottom hal ...

How to retrieve an Angular scope variable from outside the Angular framework

Seeking assistance, I have a query: Two Javascript files named A.js and B.js are at play. While A is Angular-based, B is not. However, B requires altering the value of a scope variable within A's controller. Any suggestions on how to achieve this? Man ...

Setting the data type for a React Stateless Functional Component (SFC) in TypeScript

By assigning a type of React.FC<PropsType> to a variable, it becomes recognized as a React Stateless Functional Component. Here's an example: //Interface declaration interface ButtonProps { color: string, text: string, disabled?: boolean ...

Managing shared state in Ngrx store without using ActionReducerMap

I am faced with a scenario where I have an ngrx store set up with an initial state structured like this: const state = { child1: {...}, child2: {...}, } The ActionReducerMap associated with this setup looks as follows: const ...

An unknown error has arisen: "The page https://registry.yarnpkg.com/react-native-template-react-native-template-typescript cannot be located."

Once I uninstalled the react-native-cli, I attempted to start a React Native project with a typescript template using the following command: npx react-native init MyApp --template react-native-template-typescript However, I encountered an error message: ...

Utilize AngularJS to display time in a specific format

I am trying to populate a select (dropdownlist) with hours ranging from 00 to 23 using AngularJS in the format "13:00","08:00". Here is the code snippet I have attempted: <option ng-repeat="n in [].constructor(24) track by $index" value="{{$index}}"> ...

Steps to automatically set the database value as the default option in a dropdown menu

I'm in need of assistance with a project that I'm working on. To be completely honest, I am struggling to complete it without some help. Since I am new to Angular and Springboot with only basic knowledge, I have hit a roadblock and can't mak ...

The readonly property of the ng2-currency-mask <input> element is not functioning properly

Seeking assistance with an input field that requires users to enter monetary values. I am utilizing ng2-currency-mask for this purpose, but I also need the input to be read-only. Adding the readonly attribute did not resolve the issue as the value still ch ...

Associate enumeration values with distinct data types within TypeScript

My TypeScript code snippet looks like this: enum EventType { EVENT_A = 'eventA', EVENT_B = 'eventB', ... // more event types } interface Event { type: EventType; } interface EventA extends Event { type: EventType.EVENT_A; ...

Issue in React Native and Firestore: The 'auth' property is not recognized in the specified type or an error object of unknown type

I am currently using Typescript in conjunction with Firebase and React Native. While working on the signup screen, I included Firebase like so: import * as firebase from 'firebase/app'; import 'firebase/auth'; In my onSignUp function, ...