Home > Mobile >  Creating guard in Angular
Creating guard in Angular

Time:10-29

I am creating a guard, authentication part was working but when I created auth-guard.guard.ts then I got several errors:

Error: src/app/app.module.ts:52:7 - error TS2322: Type '{ AuthService: typeof AuthService; provide: InjectionToken<HttpInterceptor[]>; useClass: typeof AuthInterceptor; multi: true; }' is not assignable to type 'Provider'. Object literal may only specify known properties, and 'AuthService' does not exist in type 'Provider'.

52       AuthService,
         ~~~~~~~~~~~


Error: src/app/auth/guard/auth-guard.ts:4:10 - error TS2305: Module '"../../shared/token.service"' has no exported member

'AuthService'.

4 import { AuthService } from '../../shared/token.service';
           ~~~~~~~~~~~


Error: src/app/auth/guard/auth-guard.ts:10:23 - error NG2003: No suitable injection token for parameter '_authService' of class

'AuthGuard'. Consider using the @Inject decorator to specify an injection token.

10   constructor(private _authService: AuthService, private _router: Router) { }
                         ~~~~~~~~~~~~

  src/app/auth/guard/auth-guard.ts:10:37
    10   constructor(private _authService: AuthService, private _router: Router) { }
                                           ~~~~~~~~~~~
    This type does not have a value, so it cannot be used as injection token.

auth/guard/auth-guard.guard.ts

import { Injectable } from '@angular/core';
    import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree,Router  } from '@angular/router';
    import { Observable } from 'rxjs';
    import { AuthService } from '../../shared/token.service';
    
    @Injectable({
      providedIn: 'root'
    })
    export class AuthGuardGuard implements CanActivate {
      constructor(private _authService: AuthService, private _router: Router) { }
      canActivate(): boolean {
        if (this._authService.isLoggedIn()) {
            return true;
        } else {
            this._router.navigate(['/login'])
            return false
        }
    }
      
    }

shared/token.service

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class TokenService {

  private issuer = {
    login: 'http://127.0.0.1:8000/api/auth/login',
    register: 'http://127.0.0.1:8000/api/auth/register'
  }

  constructor() { }

  handleData(token  : any){
    localStorage.setItem('auth_token', token);
  }

  getToken(){
    return localStorage.getItem('auth_token');
  }

  // Verify the token
  isValidToken(){
     const token = this.getToken();

     if(token){
       const payload = this.payload(token);
       if(payload){
         return Object.values(this.issuer).indexOf(payload.iss) > -1 ? true : false;
       }
     } else {
        return false;
     }
  }

  payload(token  : any) {
    const jwtPayload = token.split('.')[1];
    return JSON.parse(atob(jwtPayload));
  }

  // User state based on valid token
  isLoggedIn() {
    return this.isValidToken();
  }

  // Remove token
  removeToken(){
    localStorage.removeItem('auth_token');
  }

}

shared/auth.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

// User interface
export class User {
  name: String;
  email: String;
  password: String;
  password_confirmation: String
}

@Injectable({
  providedIn: 'root'
})

export class AuthService {

  constructor(private http: HttpClient) { }

  // User registration
  register(user: User): Observable<any> {
    return this.http.post('http://127.0.0.1:8000/api/auth/register', user);
  }

  // Login
  signin(user: User): Observable<any> {
    return this.http.post<any>('http://127.0.0.1:8000/api/auth/login', user);
  }

  // Access user profile
  profileUser(): Observable<any> {
    return this.http.get('http://127.0.0.1:8000/api/auth/user-profile');
  }

}

app.modules.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { HomeComponent } from './home/home.component';
import { RagisterComponent } from './ragister/ragister.component';
import { LoginComponent } from './login/login.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { AuthInterceptor } from './shared/auth.interceptor';
import { AuthService } from './shared/auth.service';


@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    ...
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    CarouselModule,
    FormsModule,
    CommonModule
  ],
  providers: [
    {
      AuthService,
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { PagenotfoundComponent } from './pagenotfound/pagenotfound.component';
import { RagisterComponent } from './ragister/ragister.component';
import { UserdashboardComponent } from './userdashboard/userdashboard.component';
import { AuthGuard } from './auth/guard/auth-guard.guard';

const routes: Routes = [
  {path:'',component:HomeComponent},
  {path:'login',component:LoginComponent},
  {path:'ragister',component:RagisterComponent},
  {path:'dashboard',component:UserdashboardComponent,canActivate: [AuthGuard]}
];

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

Any Solution, Thanks

CodePudding user response:

Your guard is called AuthGuardGuard instead of AuthGuard. You probably created it with

ng generate guard AuthGuard

instead of

ng generate guard Auth

You can just rename the file and class or delete/recreate (preferred solution)

CodePudding user response:

I think the problem is with the Auth Guard Class name.

You should either change the auth guard class name from AuthGuardGuard to AuthGuard

OR

Change it in routing.module.ts from

import { AuthGuard } from './auth/guard/auth-guard.guard';
{path:'dashboard',component:UserdashboardComponent,canActivate: [AuthGuard]}

TO

import { AuthGuardGuard } from './auth/guard/auth-guard.guard';
{path:'dashboard',component:UserdashboardComponent,canActivate: [AuthGuardGuard]}
  • Related