Angular Authgaurd is failing to redirect the user to the home page upon logging in, causing issues with the

Navigation Control Module

{
    path:'signin',
  component:SignInComponent
    },
  {
  path: '',
  component: MainComponent,
 canActivate:[AuthGuard],
  children: [{
    path: '',
    component: DashboardComponent
  },

SignIn component.ts

let accessKey=data["API Key"]
    let userId=data["id"]
    console.log(userId);
    console.log(accessKey);

    localStorage.setItem("key",accessKey),
  
    
    this.router.navigateByUrl('/');
    // window.location.reload(true)

AuthenticationGuard.ts

canActivate():boolean{
  if (this._authsevice.isLoggedIn()){
    return true
  }
  else{
    this._router.navigate(['/signin'])
    return false
  }
}

AuthService.ts

export class AuthService{

     isLoggedIn(){
         return !!localStorage.getItem('key')
     }
}

After successful authentication, a key is generated and saved. However, the page remains on the login screen without redirecting or navigating, prompting the AuthService to search for the key.
Even after forcibly reloading the page, it still displays the login screen. It is only after authenticating a second time that I am able to access other pages.

I am puzzled by this behavior and unsure how to prompt the Angular application to display content once the key is stored.

Answer №1

If you want to provide an URL tree as a return value, follow these steps:

canActivate(): boolean | UrlTree {
  if (this._authservice.isLoggedIn()){
    return true;
  }
  return this._router.navigate(['/login']);
}

Regarding your query:

Implement the use of an Observable for monitoring your login status using a BehaviorSubject. Return

Observable<boolean | UrlTre>
in canActivate.

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

Guide to retrieving specific attributes from an object within an array of objects using Angular Typescript

As an example, if we consider a sample JSON data retrieved from the JSONPlaceholder website at https://jsonplaceholder.typicode.com/users. [ { "id": 1, "name": "Leanne Graham", "username": "Bret&q ...

Angular validation for password and confirmation password fields

I have been working on implementing password and confirm password validation within an angular project. I recently came across a helpful answer on this thread Confirm password validation in Angular 6 that I tried to follow. Unfortunately, I am encountering ...

Merge rxjs streams, identify modifications, and yield a single result

In the context of using Angular with .net Core WebApi, let's consider the development of a time management application designed to monitor task durations. The user initiates a task on the front end which triggers a timer displaying elapsed time. The ...

What is the best method to create a TypeScript dictionary from an object using a keyboard?

One approach I frequently use involves treating objects as dictionaries. For example: type Foo = { a: string } type MyDictionary = { [key: string]: Foo } function foo(dict: MyDictionary) { // Requirement 1: The values should be of type Foo[] const va ...

Navigating to a specific div within a container with vertical overflow in an Angular application

I am working on an angular application where I have a left column with a scrollable div that has overflow-y: auto;, and a right column with bookmark links that jump to sections within the scrollable container. I am currently facing two challenges: 1 - Co ...

Navigating json information in Angular 6: Tips and Tricks

I'm currently working on an Angular 6 project and I've encountered an issue with iterating over JSON data fetched using httpClient. If anyone has a solution, I would greatly appreciate the help. The JSON data structure is as follows: Json data ...

Error message: The ofType method from Angular Redux was not found

Recently, I came across an old tutorial on Redux-Firebase-Angular Authentication. In the tutorial, there is a confusing function that caught my attention: The code snippet in question involves importing Actions from @ngrx/effects and other dependencies to ...

Utilizing Sequelize's Where clause with the flexibility of optional parameters

Can you guide me on writing Sequelize queries with optional parameters? Consider the below query example: const result : SomeModel[] = await SomeModel.findAll( {where: { id: givenId, ...

Enhancing the level of abstraction in selectors within Redux using TypeScript

Here is a custom implementation of using Redux with TypeScript and the connect method. import { connect, ConnectedProps } from 'react-redux' interface RootState { isOn: boolean } const mapState = (state: RootState) =&g ...

Angular 2 gulp task for combining multiple scss files into a single css file

app -file1 -- file1.ts -- file1.html -- file1.scss -file2 -- file2.ts -- file2.html -- file2.scss -file3 -- file3.ts -- file3.html -- file3.scss This is the structure of my project. I am currently working on consolidating all my scss files in ...

Styles are not being applied properly to mat-expansion-panel-header within a child component in CSS

One of my components utilizes MatExpansionPanel to showcase a collection of products. I have included some CSS code to conceal the overflow of each product's description. To view the current appearance, please refer to this stackblitz. In an attempt ...

Repeated values in rxjs subscription

After subscribing to an Angular service, I am encountering a problem where the results returned contain duplicate entries. Each time the service is called, the number of duplicates increases by one. To troubleshoot, I added console logs at different stage ...

Adding an authentication header in redux-api-middleware: steps and best practices

Procedure import { CALL_API } from 'redux-api-middleware'; export const MOVIES_GET_SUCCESS = 'MOVIES_GET_SUCCESS'; export const fetchMovies = () => { return { [CALL_API]: { endpoint: 'http://localhost:3005/api/mov ...

Angular 9's Jasmine Mocking Provider Featuring Unique Methods and Properties

Currently, I am attempting to mimic the functionality of the angularx-social-login npm package. My goal is for the default test to be created and passed successfully. In my test specification, the following code is included: let component: Component; l ...

Definitions for nested directories within a main index.d.ts

We have developed custom typings for the latest version of material-ui@next and successfully included them in the library during the last beta release. For those interested, you can access the index.d.ts file here. However, there seems to be a problem wi ...

solving unique errors using custom Angular directives

As I have been learning, I have discovered that validation errors in HTML are common, but I am curious about how to return custom errors. Below is a directive example: @Directive({ selector: '[verifySalaryUp]', // Attribute selector provider ...

Create a visual representation of progress over time by utilizing a single horizontally stacked bar chart with ChartJS

Can chartjs be configured to show horizontal stacked bars for continuous data over time? It's more of a progress visualization than a traditional chart. I am struggling to display multiple data points per label and have them shown as one bar. https:/ ...

Getting the value of an injected variable in a Vue.js computed method

I have utilized the provide/inject mechanism to pass data from a parent component to its grandchildren. However, in one of my components, I need to manipulate the data before rendering it in the template. My current setup looks like this: export default d ...

What is the best way to ensure that each service call to my controller is completed before proceeding to the next one within a loop in Angular?

Calling an Angular service can be done like this: this.webService.add(id) .subscribe(result => { // perform required actions }, error => { // handle errors }); // Service Definition add(id: number): Observable < any > { retu ...

Accessing a property that does not exist under the type 'string' - how to iterate through nested JSON objects

I am currently working on iterating over nested objects and storing the outer object key along with the inner nested object values in arrays. My goal is to use this data to display them in a group bar chart using chart.js. let goodArray = []; let notgoodA ...