Scandinave
Scandinave

Reputation: 1438

Angular2, How to use one template for public part and one template for Admin part

I just start playing with the new version of Angular framework. I want to have two distinct template for the admin and the public part.

I don't know how to achieve this goal. I'm thinking about a root component that will wrap the public and admin components, But i don't know how to make this work with the rooter's module.

[EDIT] I want something like this :

Root Template 
|_ public template
   |_ View 1
   |_ View 2
|_ admin template
   |_ Admin View 1
   |_ Admin View 2 

Upvotes: 1

Views: 635

Answers (2)

Scandinave
Scandinave

Reputation: 1438

I have found the way. The solution is to pass by a wrapper component. Routes can be nested with the children array parameter like this .

const appRoutes: Routes = [
  { path: 'admin', component: AdminComponent },
  { path: 'public', component: PublicComponent, children: [
    { path : '', component: HomeComponent},
    { path : 'home', component: HomeComponent},
    { path : 'api', component: ApiComponent},
    { path : 'project', component: ProjectComponent},
    { path : 'blog', component: BlogComponent},
    { path : 'about', component: AboutComponent},
  ] },
  { path : '', redirectTo: 'public/home', pathMatch: 'full'},
  { path: '**', component: PageNotFoundComponent }
];

The Public template needs the <router-outlet> tag too, like in the AppComponent template.

Upvotes: 4

DNRN
DNRN

Reputation: 2489

You could use Guards, and in your route define your routes with either admin or member.

First setup your routes, this is a very simple example you sould be able to extend it so it fits your needs:

export const routes: Routes = [
    { path: '', component: PublicComponent },
    { path: 'member', component: MemberComponent, canActivate: [AuthGuard]},
    { path: 'admin', component: AdminComponent canActivate: [AdminGuard]},  
];
export const routing = RouterModule.forRoot(routes);

Then you create two guards:

@Injectable()
export class AdminGuard implements CanActivate {

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

    canActivate() {

        if (!this._authService.isAdmin) {
            this._router.navigate(['/']);
        }

        return this._authService.isAdmin;
    }
}

The AuthGuard for members:

@Injectable()
export class AuthGuard implements CanActivate {

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

    canActivate() {
        if (!this._authService.isAuthenticated) {
            this._router.navigate(['/']);
        }

        return this._authService.isAuthenticated;
    }
}

And then you need some kind of service which holds the state of the member. Remember that providers are implanted as singletons, so the values are consistent through your application.

Here's some more info about route guards: https://angular.io/docs/ts/latest/guide/router.html

Upvotes: 1

Related Questions