Angular 2 - 内容未在路由器插座中加载

时间:2016-11-23 14:29:36

标签: javascript angular angular2-routing

我对Angular 2还很陌生,希望你们能帮助我。

我有一个相当简单的应用程序,有一个登录页面,成功登录后,用户被定向到带有侧边菜单的页面。登录屏幕没有此侧面菜单。当用户注销时,他将再次被定向到登录页面。

问题是登录后侧面菜单变得可见,但其他内容仅在刷新后可见。退出后,退出页面为空白后,只有在刷新后才会显示内容(登录页面)。我可能做错了什么,但即使看了其他问题,我也无法弄明白。

这是我的路线:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { ProfileComponent } from './profile-component/profile-component.component'
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { LoginComponent } from './login/login.component';
import { LoggedInGuard } from './logged-in/logged-in.guard';

const appRoutes: Routes = [
  {path: 'profile', component: ProfileComponent, canActivate: [LoggedInGuard]},
  {path: 'login', component: LoginComponent},
  {path: '', component: LoginComponent},
  {path: '**', component: PageNotFoundComponent},
];

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

LoginComponent

import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {LoginService} from '../login-service/login-service.service';
import {Router} from '@angular/router';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  providers: [ LoginService ]
})
export class LoginComponent implements OnInit {

  loginForm: FormGroup;
  error: String;

  constructor(private formBuilder: FormBuilder,
              private loginService: LoginService,
              private router: Router) {
  }


  ngOnInit() {
    if (this.loginService.isLoggedIn()) {
      this.router.navigate(['/profile']);
    }
    this.loginForm = this.formBuilder.group({
      username: ['', Validators.required],
      password: ['', Validators.required]
    });
  }

  login(): void {
    let self = this;
    this.loginService.login(this.loginForm.value.username, this.loginForm.value.password).subscribe(function (result) {
      if (result) {
        self.router.navigate(['/profile']);
      }

    }, function (error) {
      self.error = 'Invalid';
    });
  }
}

AppComponent HTML如下所示:

<md-toolbar color="primary" *ngIf="isLoggedIn()">
  <span>Sporter volgsysteem</span>
</md-toolbar>

<md-sidenav-layout *ngIf="isLoggedIn()">
  <md-sidenav #start mode="side" [opened]="true">
      <a routerLink="/add" routerLinkActive="active" md-button color="primary" disabled="false"><md-icon class="icon">add</md-icon><span class="nav-item">Toevoegen</span></a>
      <a routerLink="/compare" routerLinkActive="active" md-button color="primary"><md-icon class="icon">swap_horiz</md-icon><span class="nav-item">Vergelijken</span></a>
      <a routerLink="/search" routerLinkActive="active" md-button color="primary"><md-icon class="icon">search</md-icon><span class="nav-item">Zoeken</span></a>
      <a routerLink="/profile" routerLinkActive="active" md-button color="primary"><md-icon class="icon">account_box</md-icon><span class="nav-item">Profiel</span></a>
      <a routerLink="/feedback" routerLinkActive="active" md-button color="primary"><md-icon class="icon">feedback</md-icon><span class="nav-item">Feedback</span></a>
      <a routerLink="/faq" routerLinkActive="active" md-button color="primary"><md-icon class="icon">info</md-icon><span class="nav-item">FAQ</span></a>

      <div class="spacer"></div>

      <a md-button color="primary" routerLink="/login" (click)="logout()"><md-icon class="icon">exit_to_app</md-icon><span class="nav-item">Uitloggen</span></a>
  </md-sidenav>


  <router-outlet></router-outlet>
</md-sidenav-layout>


<router-outlet *ngIf="!isLoggedIn()"></router-outlet>

AppComponent

import {Component} from '@angular/core';
import {LoginService} from "./login-service/login-service.service";
import {Router } from '@angular/router'


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: []
})
export class AppComponent {

  constructor(private loginService : LoginService,
              private router: Router) {
  }

  logout() {
    this.loginService.logout();
    this.router.navigate(['/login']);
  }

  isLoggedIn() {
    return this.loginService.isLoggedIn();
  }

}

那么为什么登录后显示ProfileComponent的内容为什么,以及登出后显示登录页面的原因为什么,但刷新时都会显示?

更新

大多数人认为这是由多个未命名的router-outlet引起的,所以要验证我是否删除了其中一个出口并始终显示侧面菜单布局。当然是出于测试目的。这并没有解决问题,它给了我相同的行为:配置文件内容仅在刷新后加载。

更新2 我猜这与使用*ngIf显示router-outlet

有关

3 个答案:

答案 0 :(得分:3)

根据@bhetzie和@ jaime-torres的上述评论和我自己的假设,我进一步调查。 事实证明问题确实是双router-outlet

我的解决方案是提取LoginModule模块,然后在该模块中重定向到登录页面。在所有其他情况下,我路由到另一个名为SvsModule的模块,该模块使用侧面导航结构显示登录的内容。

因此SvsModule具有以下路由:

RouterModule.forChild([
  {path: 'svs', component: ProfileComponent, canActivate:[LoggedInGuard]},
  {path: 'svs/profile', component: ProfileComponent, canActivate:[LoggedInGuard]}
])

ProfileComponent使用以下HTML:

<md-sidenav-layout>
  <md-sidenav #start mode="side" [opened]="true">
    <md-nav-list>
      <a routerLink="/add" routerLinkActive="active" md-button color="primary" disabled="false">
        <md-icon class="icon">add</md-icon>
        <span class="nav-item">Toevoegen</span>
      </a>
      <a routerLink="/compare" routerLinkActive="active" md-button color="primary">
        <md-icon class="icon">swap_horiz</md-icon>
        <span class="nav-item">Vergelijken</span>
      </a>
      <a routerLink="/search" routerLinkActive="active" md-button color="primary">
        <md-icon class="icon">search</md-icon>
        <span class="nav-item">Zoeken</span>
      </a>
      <a routerLink="/profile" routerLinkActive="active" md-button color="primary">
        <md-icon class="icon">account_box</md-icon>
        <span class="nav-item">Profiel</span>
      </a>
      <a routerLink="/feedback" routerLinkActive="active" md-button color="primary">
        <md-icon class="icon">feedback</md-icon>
        <span class="nav-item">Feedback</span>
      </a>
      <a routerLink="/faq" routerLinkActive="active" md-button color="primary">
        <md-icon class="icon">info</md-icon>
        <span class="nav-item">FAQ</span>
      </a>

      <div class="spacer"></div>

      <a md-button color="primary" routerLink="/login" (click)="logout()">
        <md-icon class="icon">exit_to_app</md-icon>
        <span class="nav-item">Uitloggen</span></a>
    </md-nav-list>

  </md-sidenav>
  <router-outlet></router-outlet>

</md-sidenav-layout>

我会接受这个作为答案,但感谢前面提到的用户帮助我走上我的道路。

答案 1 :(得分:2)

我认为问题是双路由器出口,如上面的评论所示。我在我的项目中做了类似的事情。

这是我的解决方案:

我首先创建了一个服务来确定登录的状态(我意识到事件发射器不是很好的做法,我正在努力将其更改为行为主题):

<强> GlobalEventsManager

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


@Injectable()
export class GlobalEventsManager {
     public showNavBar: EventEmitter<boolean> = new EventEmitter<boolean>();



}

我在路由中使用了authguard来检查登录令牌是否未过期。我在这个

中使用了angular2-jwt库

<强> AuthGuard

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { tokenNotExpired } from 'angular2-jwt';
import { GlobalEventsManager } from './GlobalEventsManager';


    @Injectable()
    export class AuthGuard implements CanActivate {

        constructor(private router: Router, private globaleventsManager: GlobalEventsManager) {}
        canActivate(next: ActivatedRouteSnapshot,
                    state: RouterStateSnapshot) {

        if (tokenNotExpired('currentUser')) {
            this.globaleventsManager.showNavBar.emit(true);
            return true;

        } else {
            localStorage.removeItem('currentUser');
            this.router.navigate(['/login']);
            return false;
        }

        }


    }

当用户使用我的登录组件登录时,我将GlobalEventsManager设置为true

<强>登录

constructor(
        private router: Router,
        private authenticationService: AuthenticationService,
        private globaleventsManager: GlobalEventsManager) { }

ngOnInit() {
        // reset login status

        this.authenticationService.logout();
        this.globaleventsManager.showNavBar.emit(false);
    }

    login() {
        this.loading = true;
        this.authenticationService.login(this.model.username, this.model.password)
            .subscribe( (result) => {
                this.globaleventsManager.showNavBar.emit(true);
                this.router.navigate(['/']);

在我的导航栏中,我订阅了GlobalEventsManager并为结果设置了布尔属性:

<强>导航栏

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { NavActiveService } from '../../../services/navactive.service';
import { GlobalEventsManager } from '../../../services/GlobalEventsManager';

@Component({
  moduleId: module.id,
  selector: 'my-navbar',
  templateUrl: 'navbar.component.html',
  styleUrls:['navbar.component.css'],  
})
export class NavComponent {
  showNavBar: boolean = true;

  constructor(private router: Router,              
              private globalEventsManager: GlobalEventsManager){

    this.globalEventsManager.showNavBar.subscribe((mode:boolean)=>{
      this.showNavBar = mode;
    });

  }

}

在我的导航栏HTML中,我现在可以创建两个导航栏,一个导航栏只有一个登录导航栏,当我的authguard注意到一个toekn已过期或用户未登录时,它会显示导航栏,只需登录作为选项。登录后,GlobalEventsManager值将更改,并显示我登录的导航栏:

Navbar HTML

<div *ngIf="showNavBar">
//My logged in navbar 
</div>
<div *ngIf="!showNavBar">
//navbar that just displays login as an option
</div>

答案 2 :(得分:1)

将导航电话放在recursive Common Table Expression中。 (Angular 5)

import { NgZone } from "@angular/core";
import { Router } from "@angular/router";

constructor(
    private ngZone: NgZone,
    private router: Router
) {}

...

this.ngZone.run( () => {
    this.router.navigate(['/profile']);
});