Navigating with Angular's router occurs before the guard is fully completed

Within my Angular 8 application, the routing file is structured as below:

const myRoutes: Routes = [
  {path: '', component: FirstComponent , canActivate: [RegistrationSrcdGuard]},
  {path: 'FirstComponent ',
    component: FirstComponent ,
    canActivate: [myModuleGuard] ,
    children:[
      {path: 'SecondComponent ', component: SecondComponent , canActivate: [myModuleGuard]},
    ]
  },
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(myRoutes)
  ],
  declarations: [],
  exports: [
    RouterModule
  ]
})

In the FirstComponent.ts file, there is a navigation action defined as:

goToSecond(){
      this.router.navigate(['FirstComponent/SecondComponent '], {skipLocationChange: true});
}

The issue arises when navigating, as the processing within "myModuleGuard" seems to cause delays.

To address this, I resorted to an interim solution by modifying it as follows:

goToSecond(){
  setTimeout(() => {
      this.router.navigate(['FirstComponent/SecondComponent '], {skipLocationChange: true});
  });
}

Although functional, this workaround using setTimeout appears suboptimal.

The MyGuard used in the application is presented below:

@Injectable()
export class MyGuard implements CanActivate {
  constructor(private myService: MyService) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    const result = this.myService.getPermission();
    return result ;
  }

public getPermission() {
    let myResult : boolean
    myTreatment().subscribe(
      res => {
        return myResult = res;
      },
      err => {}
    );
    return myResult ;
  }
}

Any suggestions for improving this process?

Answer №1

To ensure efficiency in your code, make sure the myTreatment() method returns an Observable. Instead of subscribing to it within the getPermissions() method, you should return the Observable itself.

Here is how you can modify your method:

public getPermission() {
  /**
   * If myTreatment() method returns an Observable with boolean type,
   * there is no need for the pipe() method.
  */

  return myTreatment().pipe(
    map(res => {
      let result = false;
      // Add your logic here and assign a boolean value to 'result'
      return result;
    })
  );
}

Answer №2

Sentry must be:

@Injectable()
export class MyProtection implements CanActivate {

  constructor(private myAccess: MyEntry) {}

  canActivate(succeeding: ActivatedRouteSnapshot,
      status: RouterStateSnapshot): Observable<boolean> {
      return this.myAccess.getAuthorization();
  }

  canActivateChild(succeeding: ActivatedRouteSnapshot,
      status: RouterStateSnapshot): Observable<boolean> {
      return this.canActivate(succeeding, status);
  }

}

Utility should include:

public getAuthorization(): Observable<boolean> {
    return myHandling();
}

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

When attempting to run npm install for @types/jquery, an error is returned stating "Invalid name: @types/jquery"

npm install @types/jquery npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-c ...

Problem with Azure Table JavaScript Solution

When attempting to utilize JavaScript to access Azure Storage Tables, I encountered an error that reads: "Error getting status from the table: TypeError: tableServiceClient.getTableClient is not a function." Despite finding multiple successful examples onl ...

Enhance Accordion Component with New Information

I am in the process of updating an accordion based on search results returned as an array. Initially, the accordion displays the full set of results from a service, but when I perform a search, the console shows the correct values, however, the ngModel i ...

What is the process for releasing an NPM package to the NPM registry rather than the GitHub registry?

I have developed an NPM package available at - (https://github.com/fyndreact/nitrozen) The package was successfully published on the Github registry (), but I am looking to publish it on the NPM registry. However, I cannot locate the package in the NPM r ...

Animating transitions on a dynamic Bootstrap navbar using jQuery

I have the code attached here, and I successfully changed the color of the navbar and logo when scrolling down. However, I am looking to add a transition effect when this change occurs. I experimented with various transition options in CSS, but unfortunat ...

Learning the implementation of uib-tabset in Angular 2 with ng-bootstrap

Currently, I am working on an angular2 project and I am curious to know if there is a way to utilize uib-tabset in angular2. In the past, when I was using angularjs, I could easily use ng-bootstrap. This allowed me to incorporate <uib-tabset></u ...

AngularJS deferred rendering (not deferred loading views)

Imagine having over 3000 items to display within a fixed-height div using an ng-repeat and setting overflow: auto. This would result in only a portion of the items being visible with the rest accessible via scrollbar. It's anticipated that simply run ...

Troubleshooting guide for resolving parse error when installing Open MCT

Hi there! I'm currently in the process of installing NASA's Open MCT (Link) but have hit a roadblock with errors during installation. Upon running npm install, I encountered the following error message: { Error: Parse error using esprima for fil ...

Unpacking Reddit's JSON data in a Node environment proves challenging as the Javascript parser seems to have a distaste for

Hey there, I hope everything is going well! I've been working on a project that involves scanning the JSON data from reddit.com/r/pics. My goal is to extract a random image and display it on a webpage. The issue I'm facing is that Reddit's ...

The success variable of the Ajax running continuously in a loop is not being refreshed

Within this code snippet, a for loop is utilized to iterate through an array called netnos[] and update the variable 'nets' for each item. Ajax is then invoked to call a PHP script that generates a listing, which is successfully outputted to the ...

Hidden content from Vue router view

My goal is to have the navigation pane overlaying the content of the page, but instead, it is being appended to the bottom where the end of the navigation drawer would be. I've experimented with different variations to display data using navigation dr ...

Is it a bad idea to incorporate JavaScript functions into AngularJS directives?

I came across this snippet of code while working with ng-repeat: <div ng-show="parameter == 'MyTESTtext'">{{parameter}}</div> Here, parameter represents a string variable in the $scope... I started exploring if it was possible to c ...

Is there a way to check if a user has previously visited a URL and automatically redirect them back to that page if they have

I'm looking for a way to detect if a user has already opened a specific link or URL in their browser tab. Is it possible to redirect the link to an active tab if the URL is already open? For example, if a user clicks on a link and JS code opens a new ...

"Utilizing the power of mapping in React to dynamically generate and return an

Hello everyone! I'm currently working on a project where I am making a get request to a Google API and fetching some data. Initially, the state value is empty, but after receiving the ajax response, I expect the state values to be updated using setSta ...

What is the significance of utilizing generic types as values within a generic class?

Why is the compiler giving an error for the following code T' only refers to a type, but is being used as a value here: class Factory<T> { create(TCreator: (new () => T)): T { return new TCreator(); } test(json: string) ...

What advantages does ViewContainerRef offer compared to *ngif?

Instead of just using *ngIf to conditionally include my-awesome-component, I could also use ViewContainerRef. However, I'm not sure what makes it so special compared to *ngif. Can someone please point out the advantages and disadvantages of both metho ...

Looking for assistance with an Angular2 post request?

I'm having an issue with a post request to obtain a token granting access to another access token. Each time I attempt to make the post request, I encounter an error stating that the access_token property is trying to read something undefined. It seem ...

Looking to find the video code in the page source and figure out how to get the video to play

I have a requirement where I must embed the video code directly in a blog post. After figuring out the necessary code for the video and saving it in a html file named video.html, I encountered an issue when trying to upload the file to the blog. Only the ...

Tips for exporting data to a JSON file using the Google Play Scraper in NodeJS

Recently, I've been exploring the Google Play Scraper and I'm in need of a complete list of all appIds using NodeJS. The issue I'm facing is that it only outputs to console.log. What I really require is to save this output to JSON and then c ...

Choose the initial full text that corresponds with a portion of the text

I am currently working on a page with multiple <string> tags containing different strings, like 'Is this a String?  Yes'. My goal is to use JQuery to locate the first instance of 'Is this a String?  ' and extract either ...