Elements do not disappear once I have logged in with authService

I'm having trouble with the login and register links in the navbar. I want them to disappear when a user is logged in. Even after following a Youtube tutorial to resolve this issue, it's still not working.


    <li *ngIf="authService.loggedIn()" [routerLinkActive]="['active']" [routerLinkActiveOptions] = "{exact:true}"><a  [routerLink]= "['/dashboard']">Dashboard</a> </li>
          <li *ngIf="authService.loggedIn()" [routerLinkActive]="['active'] " [routerLinkActiveOptions] = "{exact:true}"><a  [routerLink]= "['/profile']">Profile</a></li>
          <li *ngIf="!authService.loggedIn()" [routerLinkActive]="['active']" [routerLinkActiveOptions] = "{exact:true}"><a  [routerLink]= "['/login']">Login</a></li>
          <li *ngIf="!authService.loggedIn()" [routerLinkActive]="['active']" [routerLinkActiveOptions] = "{exact:true}"> <a  [routerLink]= "['/register']">Register</a></li>
          <li *ngIf="authService.loggedIn()"><a (click)="onLogOutClick()" href="#">Logout</a></li>

Currently, both logout and profile are hidden at all times and do not appear when I am logged in.

This is how the Auth.service.ts file is structured:


import { Http, Headers } from '@angular/http';
import { map } from 'rxjs/operators';
import { tokenNotExpired } from 'angular2-jwt';


@Injectable()
export class AuthService {
authToken: any;
user: any;

  constructor(private http: Http) { }

  registerUser(user){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:3000/users/register', user, {headers: headers})
    .pipe(map(res => res.json()));
  }

  authenticateUser(user){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:3000/users/authenticate', user, {headers: headers})
    .pipe(map(res => res.json()));
  }

  storeUserData(token, user){
    localStorage.setItem('id_token', token);
    localStorage.setItem('user', JSON.stringify(user));
    this.authToken = token;
    this.user = user;
  } 

  loggedIn(){
    return tokenNotExpired();
  }
  logout(){
    this.authToken = null;
    this.user = null;
    localStorage.clear();
  }

  getProfile(){
    let headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type', 'application/json');
    return this.http.get('http://localhost:3000/users/profile', {headers: headers})
    .pipe(map(res => res.json()));
  }

  loadToken(){
    const token = localStorage.getItem('id_token');
    this.authToken = token;
  }
}

Answer №1

It is recommended to utilize token in place of id_token within the storeUserData function.

For more information and a thorough explanation, please refer to this link.

Answer №2

identifier is the default term used by the following libraries to access local storage. If you prefer to use a custom term, you can utilize the methods outlined below.

angular2-jwt is no longer supported; opt for @auth0/angular-jwt

Define your token retriever in JwtModule @auth0/angular-jwt

https://www.npmjs.com/package/@auth0/angular-jwt

export function retrieveToken() {
  return localStorage.getItem('id_token');
}

JwtModule.forRoot({
  config: {
    tokenGetter: retrieveToken,
    whitelistedDomains: ['example.com'],
    blacklistedRoutes: ['example.com/examplebadroute/']
  }
})

If you still wish to use the outdated version, stick with angular2-jwt

https://www.npmjs.com/package/angular2-jwt

import { AuthHttp, AuthConfig } from 'angular2-jwt';

export function authenticationServiceFactory(http: Http, options: RequestOptions) {
  return new AuthHttp(new AuthConfig({
    tokenName: 'token',
        tokenGetter: (() => localStorage.getItem('id_token')),
        globalHeaders: [{'Content-Type':'application/json'}],
    }), http, options);
}

@NgModule({
  providers: [
    {
      provide: AuthHttp,
      useFactory: authenticationServiceFactory,
      deps: [Http, RequestOptions]
    }
  ]
})
export class AuthModule {}

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

AngularJS 2 TypeScript structure

My application includes a user service for managing user operations and an interface for the user object. user.service.ts import {Injectable} from 'angular2/core'; export interface User { name: string; email?: string; picture?: string; } ...

What is the best way to retrieve the initial value from a sequence of linked observables?

My current project involves utilizing the Angular Model Pattern. The goal I am aiming for is as follows: after adding an article of a specific type, two tasks should be carried out: Refresh the newspaper to update the model: model.Newspaper; Once the ne ...

Verification Tool for Detecting Repeated Spaces

I am working towards developing an Angular Validator that will prevent consecutive spaces from being entered. At the moment, I have implemented Validators.pattern('^[a-zA-Z0-9]+( [a-zA-Z0-9]+)*$'), which successfully addressed the issue. However ...

The Axios function is unable to read the 'Ok' value because of undefined properties

I suspect there is something missing in my argument, but I am attempting to call HttpStatusCode.Ok from the Axios Enum. Here is how I have implemented it: import { HttpStatusCode } from 'axios' console.log(HttpStatusCode.Ok) However, I encounte ...

Tips for incorporating a reference into a styled component div in a React application using TypeScript

Looking to include a reference to a styled component div. Here is the code snippet: const DragAndDrop: React.FC<any> = props => { const divRef= React.createRef(); return ( <Zone ref={divRef}/> ); } Encountering thi ...

How to disable animation dynamically in Angular during runtime

When I launch the application, I know I can utilize BrowserAnimationModule and NoopAnimationsModule. In the event that a user requests to disable animations for ADA compliance and other reasons, what is the best approach to turn off animations at runtime ...

Guide to eliminating text following a space within a string in Angular 8

Having trouble trying to capitalize the first letter after an underscore in a string using Angular 8. Can anyone help me find a solution? app.component.ts: let content="power_managment 0vol"; alert(content.split( ).[0]); // desired output: "powerManagmen ...

I noticed that the ./src/main.js file is present in multi (webpack)-dev-server/client, but unfortunately I do not have the main.js file. I am

I'm currently working on a Vue.js 3 application demo using tailwind and typescript. Each time I try to run the app, I encounter an error message that says: This relative module was not found: * ./src/main.js in multi (webpack)-dev-server/client?https ...

I find that ChangeDetectionStrategy.OnPush does not function as anticipated

Exploring the performance boost of ChangeDetectionStrategy.OnPush in Angular 2 (detailed here) has been my recent focus. However, I've encountered an interesting scenario. In my code, I have the parent component AppComponent: @Component({ selector ...

Attempting to transpile JavaScript or TypeScript files for compatibility within a Node environment

Our node environment requires that our JavaScript files undergo Babel processing. Figuring out how to handle this has been manageable. The challenge lies in the fact that we have a mix of file types including .js, .jsx, .ts, and .tsx, which is not subject ...

Navigating the Relationship Between Strings and Objects in Angular

I am looking for a way to create a mapping from a string to an object in Angular, similar to how it is done in JAVA. Here is an example of the json String I have: {"policyNumber":"1234", "firstName":"archi"} The TypeScript Object looks like this: export ...

`Successful redirection after saving`

I'm looking for a solution to redirect/stay on the CREATE_PAGE in Angular/TypeScript when inserting a new item. I've tried using window.open and href functions without success. If you have any suggestions, please share them :) private onSa ...

Retrieve the value of a nested property using the dynamic string literals of an object's nested keys

I am looking to retrieve a value (object) using the keys of a nested object structure. For instance, imagine I have an object that contains various car brands. Each brand consists of multiple models, and each model has specific information about the car. ...

Is it possible to modify the authenticated user ID right before its creation in Firebase, especially when the user is being created via the Facebook provider?

As we transition our MongoDB database to Firebase with Firestore, we are facing the challenge of integrating Firebase authentication for our users. Currently, we store user data in Firestore and want to utilize Firebase authentication for user logins. Each ...

Tips for solving caching problems in an Angular application on a web browser

My Angular application undergoes a deployment pipeline where we utilize the "ng build --prod" command to build the application. Each time we make code changes, this command generates a unique hashcode for the build files. However, we are encountering an ...

What is the best way to retrieve information from a mat-option loop?

Utilizing mat-select to fetch options from a database, the table also includes an images column. How can I change the image outside of mat-select when the mat-option is changed? I am attempting to extract the value outside of the mat-option loop. I have ...

Tips for implementing lazy loading for a section of a template in Angular 2

I have an Angular 2 component that has several sub-components within it. Some of these sub-components are expensive to load and may not always be necessary, especially if the user doesn't scroll far enough down the page. Although I am familiar with l ...

Is it possible to dynamically name keys in objects using template literals in Typescript?

Can the scenario below be achieved? type test = <T extends string>(key: T, object: { [`${T}`]: number }) => void ^^^^^^^^ I am aware that we can assign type literal values using that syntax, but af ...

Incorporating numerous query parameters in Angular version 14

I am currently working on developing a multi-item filter feature for my application and I am faced with the challenge of sending multiple query parameters in the API request to retrieve filtered items. My main concern is whether there is a more efficient ...

Setting a default value for a null Select Option in React: a guide

I am currently working with an array of values and looping through them to display in a Select Option. <Form.Item label="Status"> <Select value={user.status} onChange={handleStatusChange} > ...