Angular project structure

0

I am analyzing how to start a project with Angular.

In a previous one, which we have currently underway, mounted with AngularJS 1.5, with a structure similar to the one I am looking for, which is a login screen, which, if the user exists, passes you to a website.

This was structured with an abstract template, which has 2 children one for the login and one for the template with menu, which is used throughout the internal structure of the web.

I have the doubt that in Angular 4 the project should not be structured like this. Can you give me a hand on how to propose this structure?

    
asked by Diego 28.08.2017 в 22:08
source

1 answer

1

Given that you use the router in your Angular 2+ project, you can choose to have your authentication component and your other intranet components routed and so from a third component, for example app-component have there the% co_of angle% that controls what to display.

  

AppComponent.html

<app-menu-intranet *ngIf="authenticated"></app-menu-intranet>
<router-outlet></router-outlet>
  

LoginComponent.html

<form (submit)="onSubmit()">
  <input type="email" [(ngModel)]="email">
  <input type="password" [(ngModel)]="password">
  <button>LOGIN</button>
</form>
  

Dashboard.html

<main>
  <h1>Bienvenid@</h1>
</main>

Here the important thing is to have Guards , which are nothing more than the interceptors or middlewares of the angular routes. This is where you decide if the dashboard can be seen only if the user is authenticated.

const routes: Route = [
    { path: 'login', component: LoginComponent },
    { path: 'dashboard', component: DashboardComponent, canActivate: [ AuthGuard ] },
    { path: '**', pathMatch: 'full', redirectTo: 'login' }
];

Update

An example of a Guard

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router, private authService: AuthService) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (!this.authService.isAuthenticated()) {
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }

}
    
answered by 28.08.2017 / 22:40
source