famas23
famas23

Reputation: 2290

Protect angular derective via guard

I have kind of ChatbotComponent that is not attached to any route configuration.

@Component({
  selector: 'app-chatbot',
  templateUrl: './chatbot.component.html',
  styleUrls: ['./chatbot.component.css'],
  providers: [UsersService, OrganizationService]
})

The directive, is called under app.compononent.html covered by app module:

<app-logo></app-logo>
<router-outlet></router-outlet>
<app-footer></app-footer>
<app-chatbot></app-chatbot>

This is my routing.yaml

const routes: Routes = [
  { path: '',  component: LoginComponent, pathMatch: 'full', canActivate: [AuthenticationGuard]},
  { path: 'accueil',  component: AccueilComponent, canActivate: [AuthenticationGuard] },
  { path: '**', redirectTo: '' }
];



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

I'm asking is there any way to protect the ChatbotComponent via my AuthenticationGuard in order to stop api calls fired under the compononent !

This is a small vision about my dependencies:

+-- @angular/[email protected]
+-- @angular/[email protected]
| +-- @angular-devkit/[email protected]
| +-- @angular-devkit/[email protected]
| +-- @angular-devkit/[email protected]
| +-- @schematics/[email protected]
+-- @angular/[email protected]
+-- @angular/[email protected]
+-- @angular/[email protected]
+-- @angular/[email protected]
+-- @angular/[email protected]
+-- @angular/[email protected]
+-- @angular/[email protected]
+-- @angular/[email protected]
+-- @angular/[email protected]
+-- @angular/[email protected]
+-- [email protected]

Thanks

Upvotes: 0

Views: 50

Answers (1)

Sherif Elmetainy
Sherif Elmetainy

Reputation: 4502

You can simply use *ngIf

<app-chatbot *ngIf="isAuthenticated"></app-chatbot>

Where you should define isAuthenticated in your app.component.ts and assign true if the user is authenticated, and false otherwise.

Edit: For example in your app.component.ts

export class AppComponent implements OnInit {
    public isAuthenticated: boolean = false;

    constructor(
        private authenticationService: AuthenticationService
    ) {
    }

    // Authentication service has an obsevable authenticated that emits a value when the user authentication status changes.
    // in ngOnInit subscribe to that value
    public ngOnInit(): void {
        this.authenticationService.authenticated$.subscribe((val) => {
             this.isAuthenticated = val;
        });
    }
}

Upvotes: 1

Related Questions