wiele układów dla różnych stron w angular 2

Buduję aplikację angular2.

Mam stronę logowania-tylko 2 wejścia (bez nagłówka bez stopki bez paska bocznego)

Po zalogowaniu użytkownik powinien przejść do strony z nagłówkiem, stopką i prawym paskiem nawigacyjnym.

Jedyną rzeczą, która zmienia się w wewnętrznej stronie, jest zawartość prawej strony.

Mam app.component

import { Component } from '@angular/core';
import {ViewEncapsulation} from '@angular/core';

@Component({
    selector: 'pm-app',
    template: `
    <div>
        <router-outlet></router-outlet>
     </div>
     `,
     styleUrls:["app/app.component.css"],
      encapsulation: ViewEncapsulation.None
})
export class AppComponent {
    pageTitle: string = 'Acme Product Management';
}

Rozumiem tę aplikację.komponent jest jak Strona główna, gdzie można dodać nagłówek i stopkę, a {[1] } jest gdzie zawartość zmienia się na podstawie / align = "left" /

Moje proste pytanie brzmi: jak zrobić jeden układ dla strony logowania i inny układ z nagłówkiem, stopką i prawym paskiem do strony wewnętrznej?

 41
Author: Daniel, 2016-11-09

4 answers

Można używać tras potomnych do używania różnych układów dla różnych widoków.

Jest to bardzo proste, ponieważ nie jest to możliwe.]}

Lubię używać tras potomnych do oddzielania bezpiecznych stron i niezabezpieczonych stron w moich aplikacjach angular 2.

W mojej aplikacji root mam dwa katalogi

/Public

&

 /Secure

Teraz w katalogu głównym mam również

/app.routing.ts

Stamtąd tworzę folder layoutów,

/layouts

W tym katalogu I create

/layouts/secure.component.ts
/layouts/secure.component.html

&

/layouts/public.component.ts
/layouts/public.component.html

Od tego momentu mogę przekierować Moje trasy do jednego z dwóch układów w zależności od tego, czy strona ma być Bezpieczna czy Publiczna. Robię to, tworząc trasę do każdego układu w moich root routes.plik ts.

/app.trasy.ts

const APP_ROUTES: Routes = [
    { path: '', redirectTo: '/home', pathMatch: 'full', },
    { path: '', component: PublicComponent, data: { title: 'Public Views' }, children: PUBLIC_ROUTES },
    { path: '', component: SecureComponent, canActivate: [Guard], data: { title: 'Secure Views' }, children: SECURE_ROUTES }
];

Zauważ, że rejestruję trasy dziecka dla każdego układu. Jest to wyeksportowana wartość każdego osobnego pliku trasy. Jeden jest w katalogu publicznym, a drugi w bezpiecznym katalog.

/public / public.trasy.ts

export const PUBLIC_ROUTES: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'p404', component: p404Component },
    { path: 'e500', component: e500Component },
    { path: 'login', component: LoginComponent },
    { path: 'register', component: RegisterComponent },
    { path: 'home', component: HomeComponent },
    { path: 'benefits', component: BenefitsComponent },
    { path: 'services', component: ServicesComponent },
    { path: 'education', component: EducationComponent },
    { path: 'products', component: ProductsComponent },
    { path: 'fcra', component: FcraComponent },
    { path: 'croa', component: CroaComponent },
    { path: 'building', component: BuildingComponent },
    { path: 'tips', component: TipsComponent },
    { path: 'maintenance', component: MaintenanceComponent }
];

Wszystkie te trasy są teraz dostępne jako trasy dziecięce dla mojego publicznego układu. Co teraz prowadzi nas do ochrony naszych bezpiecznych poglądów.

Więc w bezpiecznym katalogu zasadniczo robię to samo,

/secure / secure.trasy.ts

export const SECURE_ROUTES: Routes = [
    { path: '', redirectTo: 'overview', pathMatch: 'full' },
    { path: 'items', component: ItemsComponent },
    { path: 'overview', component: OverviewComponent },
    { path: 'profile', component: ProfileComponent },
    { path: 'reports', component: ReportsComponent },
    { path: 'recommendations', component: RecommendationsComponent },
    { path: 'score-simulator', component: ScoreSimulatorComponent },
    { path: 'payment-method', component: PaymentMethodComponent },
    { path: 'lock-account', component: LockAccountComponent }
];

To pozwala mi używać auth do ochrony tych dziecięcych dróg. Jeśli pamiętasz w

/app.trasy.ts zrobiliśmy to dla bezpieczeństwa trasy,

{ path: '', component: SecureComponent, canActivate: [Guard], data: { title: 'Secure Views' }, children: SECURE_ROUTES }

Zwróć uwagę na [Guard]. Pozwala nam to chronić wszystkie trasy potomne dla bezpiecznego układu. To jeden z powodów, dla których korzystam z tras dziecięcych. Mógłbym dać ci o wiele więcej, ale uważam, że to najbardziej rozsądne wyjaśnienie.

Aby posunąć sprawy o mały krok dalej i umieścić to w perspektywie dla Ciebie, oto jak ja [Guard] bezpieczne strony. Tworzenie serwisu i implementing CanActivate

@Injectable()
export class Guard implements CanActivate {

    constructor(protected router: Router, protected auth: Auth ) {}

     canActivate() {
        if (localStorage.getItem('access_token')) {
            // logged in so return true
            return true;
        }
        // not logged in so redirect to login page
        this.router.navigate(['/home']);
        return false;
    }
}

To pozwala na serwowanie publicznego układu z <router-outlet></router-outlet>, a następnie użycie innego nagłówka i stopka w układzie. Następnie ponownie użyj <router-outlet></router-outlet> w bezpiecznym układzie i oczywiście innego nagłówka i stopki. Daj mi znać, jeśli zostawiłem coś niejasnego, a zaktualizuję odpowiedź.

 53
Author: wuno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-09 14:01:20

Możesz rozwiązać swój problem za pomocą tras potomnych.

Zobacz demo robocze na https://angular-multi-layout-example.stackblitz.io / lub Edytuj w https://stackblitz.com/edit/angular-multi-layout-example

Ustaw trasę jak poniżej

const appRoutes: Routes = [

    //Site routes goes here 
    { 
        path: '', 
        component: SiteLayoutComponent,
        children: [
          { path: '', component: HomeComponent, pathMatch: 'full'},
          { path: 'about', component: AboutComponent }
        ]
    },

    // App routes goes here here
    { 
        path: '',
        component: AppLayoutComponent, 
        children: [
          { path: 'dashboard', component: DashboardComponent },
          { path: 'profile', component: ProfileComponent }
        ]
    },

    //no layout routes
    { path: 'login', component: LoginComponent},
    { path: 'register', component: RegisterComponent },
    // otherwise redirect to home
    { path: '**', redirectTo: '' }
];

export const routing = RouterModule.forRoot(appRoutes);

Rekomendowany numer referencyjny: http://www.tech-coder.com/2017/01/multiple-master-pages-in-angular2-and.html

 18
Author: Rameez Rami,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-15 15:12:30

Możesz mieć wiele gniazd routera i przekierowania tam, gdzie chcesz. Na przykład strona logowania może być Stroną docelową, jeśli użytkownik nie jest zalogowany i jeśli use jest zalogowany, przekierowujesz użytkownika na stronę wzorcową, na której masz nagłówek i stopkę, a wszystkie inne strony mogą być potomkami tego komponentu. Na przykład mamy naszą aplikację w ten sposób

<my-app></my-app>

W moim-komponencie masz

<router-outlet></router-outlet> ¨ masz jeden komponent logowania i możesz użyć tego routingu dla tej strony w ten sposób

 { path: '', component: LoginComponent}

Jak powiedziano wcześniej może to być strona docelowa i nie chcesz pokazywać niczego innego, niż dane logowania. Po zalogowaniu użytkownik przekierowuje użytkownika do komponentu głównego i komponent główny będzie miał routing w ten sposób

{ path: 'masterpage', component: MasterComponent}

I główny komponent będzie miał również gniazdo routera

<router-outlet></router-outlet>

Teraz, gdy chcesz pokazać użytkownikowi inne strony, takie jak o nas. następnie przekierujesz użytkownika na stronę O nas w ten sposób

{ canActivate: [AuthGuard], component: MasterComponent , path: 'masterpage',
  children:[
           {   canActivate: [AuthGuard],
               component: AboutUsComponent ,
               path: 'aboutus'
           }]
}

Oraz w ten sposób będziesz miał szczegóły, takie jak nagłówek i stopka w każdym miejscu, w którym używasz nawigacji. Mam nadzieję, że to pomoże!

 1
Author: Jorawar Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-09 14:23:32

Zwróć uwagę na gniazdo routera. Tam będą wyświetlane Twoje treści. To jest przykład mojej aplikacji.komponent.html. W tym przypadku przekierowanie jest do domu.komponent i jego wyświetlane w gniazdku routera.

<div class="ui-grid ui-grid-responsive ui-grid-pad">
    <div class="ui-g borderDiv" [ngStyle]="appPageHeaderDivStyle">
        <div class="ui-g-12" *ngIf="!isLoggedIn">
            <div class="ui-g">
                <div class="ui-xl-2">
                    <img class="logo" src="./app/resources/KetoLightLogo.png">
                </div>
                <div class="ui-xl-7">
                </div>
                <div class="ui-xl-3 ui-g-nopad" style="width: 320px; margin-left: 80px; float: right; ">
                    <div>
                        <p-menubar class="pMenuBar" [model]="items"></p-menubar>
                    </div>
                </div>
            </div>
        </div>

        <div class="ui-g-12" *ngIf="isLoggedIn">
            <div class="ui-g">
                <div class="ui-xl-2">
                    <img class="logo" src="assets/KetoLightLogo.png">
                </div>
                <div class="ui-xl-4">
                    <label class="ui-widget loggedInLabel">Logged in as: [email protected]</label>
                </div>
                <div class="ui-xl-6 ui-g-nopad" style="width: 525px;  margin-left: 270px; float: right; ">
                    <p-menubar [model]="items"></p-menubar>
                </div>
            </div>
        </div>
    </div>
</div>

<router-outlet></router-outlet>

<div class="ui-grid ui-grid-responsive ui-grid-pad">
    <div class="ui-g borderDiv" [ngStyle]="appPageHeaderDivStyle">
        <div class="ui-g-12">
            <div class="ui-g">
                <div class="ui-g-12 ui-md-12 ui-lg-12">
                    <div class="ui-g-row">
                        <div class="ui-g-12">
                            <div class="ui-g-12 ui-md-12 ui-lg-12">
                                <div class="ui-g-1 ui-md-4 ui-lg-5">
                                </div>
                                <div class="ui-g-10 ui-md-4 ui-lg-2">
                                    <p class="copyright">Copyright 2016 Xamlware, Inc.</p>
                                    <p class="copyright2">All rights reserved</p>
                                </div>
                                <div class="ui-g-1 ui-md-4 ui-lg-5">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
 0
Author: John Baird,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-09 14:02:48