Routerlink不起作用,但是如果我在url中输入路径,则可以进入视图

问题描述

在我的主要路线中,我有很多模块,一些是延迟加载的,其他是预加载策略,也有一些用于简单组件的路线。有些路由具有AuthGuard。

当我单击带有Routerlink的元素时,它会转到Authguard,但会在此处停止,不会加载视图,并且网址也不会更改。

如果我在url中输入路由,并且页面正确加载。

app.module.ts

   import { browserModule } from '@angular/platform-browser';
import { NgModule,LOCALE_ID,CUSTOM_ELEMENTS_SCHEMA,Injectable,Injector,Inject,InjectionToken,ErrorHandler } from '@angular/core';
import { registerLocaleData,CommonModule } from '@angular/common';
import { HttpClientModule,HTTP_INTERCEPTORS } from '@angular/common/http';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import localeEsArs from '@angular/common/locales/es-AR';

import { ToasterModule,ToasterService } from 'angular2-toaster';

registerLocaleData(localeEsArs);

import { environment } from '../environments/environment';

import { routing } from './app.routing';

//Components and Services
import { AppComponent } from './app.component';
import { CallbackComponent } from './callback.component';
import { disableControlDirective } from './directives/disable.directive';

import { AuthGuard } from './auth.guard';
import { EventEmitterService } from './services/event.emitter.service';
import { GenericModal } from './modals/genericmodal/modal.component';

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

//services
import { AuthService } from './services/auth.service';
import { UserService } from './services/user.service';
import { BookingService } from './services/booking.service';

//Material Angular
import { browserAnimationsModule } from '@angular/platform-browser/animations';
import { MatInputModule,MatFormFieldModule,MatExpansionModule,MatDividerModule,MatTableModule,MatButtonModule,MatMenuModule,MatSelectModule,MatSidenavModule,MatIconModule,MatToolbarModule,MatCheckBoxModule,MatTabsModule,MatPaginatorModule,MatButtonToggleModule,MatDialogModule,MatAutocompleteModule,MatNativeDateModule,MatProgressspinnerModule,MatTableDataSource,MatListModule,MatSliderModule,MatProgressBarModule,MatSlidetoggleModule,MatStepperModule,MaTradioModule,MatCardModule,MatBadgeModule
} from '@angular/material';

import { UserMetadataAdapter } from './core/adapter/userMetadataAdapter';
import { PlaceAdapter } from './core/adapter/placeAdapter';
import { Calendaradapter } from './core/adapter/calendaradapter';
import { PlaceGoogleAdapter } from './core/adapter/placeGoogleAdapter';
import { PredictionAdapter } from './core/adapter/predictionAdapter';
import { FingerPrintsAdapter } from './core/adapter/fingerPrintsAdapter';
import { GoogleAnalyticsService } from './services/googleAnalytics.Service';
import { SimpleAlgorithms } from './core/algorithms/simpleAlgorithms';
import { About } from './about/about.component';
import { PageNotFoundComponent } from './error/page-not-found/page-not-found.component';
import { DragToSelectModule } from 'ngx-drag-to-select';


import { InfiniteScrollModule } from 'ngx-infinite-scroll';



import { ReviewAdapter } from './core/adapter/reviewAdapter';
import { UserAdapter } from './core/adapter/userAdapter';

import { CookieService } from './services/cookieService';
import { ConfirmationDialog } from './entities/shared/dialogs/confirmation-dialog/confirmation-dialog';
import { BlogComponent } from './blog/blog.component';
import { BlogPostComponent } from './blog-post/blog-post.component';
import { CurrencyAdapter } from './core/adapter/currencyAdapter';
import { BellNotifyComponent } from './bell-notify/bell-notify.component';
import { NotificationAdapter } from './core/adapter/notificationAdapter';
import { OnScrollLoadComponent } from './shared/onscroll-load/onscroll-load.component';
import { SafePipe } from './pipes/safe.pipe';
import { MapLoaderModule } from './loaders/map/map-loader.module';
import { CroppingLoaderModule,GlobalVariables } from './loaders/cropping/cropping-loader.module';
import { UseractivitylogService } from './services/activitylog/user-activity-log.service';
import { UseractivitylogAdapter } from './core/adapter/activity-log/useractivitylogAdapter';
import { DialogTermsAndCondOverview } from './new-place-module/new-place/new-place.component';
import { BusinessInfoService } from './services/businessInfo.service';
import { PostAdapter } from './core/adapter/postAdapter';
import { EmitterService } from './services/emitter.service';
import { DateTimeService } from './services/datetime/date-time.service';
import { HomeModule } from './home-module/home.module';
import { AppCustomPreloader } from './app-custom-preloading';
import { HttpErrorInterceptor } from './http-error-interceptor';

// Rollbar Init----------------------------------------------------------
import Rollbar from 'rollbar';
import { NotificationService } from './services/notification/notification.service';
import { RouterModule } from '@angular/router';
import { Help } from './help/help.component';

const rollbarConfig = {
  accesstoken: environment.rollbarLog.accesstoken,captureUncaught: true,captureUnhandledRejections: true,environment: environment.rollbarLog.envName
};

export const RollbarService = new InjectionToken<Rollbar>('rollbar');

@Injectable()
export class RollbarErrorHandler implements ErrorHandler {
  constructor(@Inject(RollbarService) private rollbar: Rollbar) { }

  handleError(err: any): void {
    if (environment.production)
      this.rollbar.error(err.originalError || err);
  }
}

export function rollbarFactory() {
  return new Rollbar(rollbarConfig);
}

//Rollbar End-------------------------------------------------------------------------------

@NgModule({
  exports: [
    MatInputModule,MatBadgeModule
  ]
})
export class MaterialAngularModules { }

@NgModule({
  declarations: [
    AppComponent,disableControlDirective,CallbackComponent,GenericModal,PageNotFoundComponent,About,Help,ConfirmationDialog,BlogComponent,BlogPostComponent,BellNotifyComponent,OnScrollLoadComponent,DialogTermsAndCondOverview
  ],entryComponents: [GenericModal,DialogTermsAndCondOverview],imports: [
    browserModule,browserAnimationsModule,MaterialAngularModules,HttpClientModule,CommonModule,FormsModule,RouterModule,ReactiveFormsModule,routing,CroppingLoaderModule,DragToSelectModule.forRoot(),InfiniteScrollModule,ToasterModule.forRoot(),MapLoaderModule,NgbModule,HomeModule
  ],exports: [],providers: [{ provide: LOCALE_ID,useValue: 'es-AR' },AuthService,AuthGuard,EventEmitterService,EmitterService,GoogleAnalyticsService,UserMetadataAdapter,PlaceAdapter,Calendaradapter,PlaceGoogleAdapter,PredictionAdapter,FingerPrintsAdapter,SimpleAlgorithms,ReviewAdapter,UserAdapter,UserService,UseractivitylogService,CookieService,NotificationService,BusinessInfoService,CurrencyAdapter,NotificationAdapter,UseractivitylogAdapter,PostAdapter,AppCustomPreloader,DateTimeService,{

      provide: HTTP_INTERCEPTORS,useClass: HttpErrorInterceptor,multi: true

    },{ provide: ErrorHandler,useClass: RollbarErrorHandler  },{ provide: RollbarService,useFactory: rollbarFactory }
  ],schemas: [CUSTOM_ELEMENTS_SCHEMA],bootstrap: [AppComponent]
  
})
export class AppModule { }

app.route.ts

import { AppComponent } from './app.component';
import { Routes,PreloadAllModules } from '@angular/router';
import { ModuleWithProviders } from '@angular/core';
import { AuthGuard } from './auth.guard'; 
import { CallbackComponent } from './callback.component';
import { About } from './about/about.component';
import { PageNotFoundComponent } from './error/page-not-found/page-not-found.component';
import { BlogComponent } from './blog/blog.component';
import { BlogPostComponent } from './blog-post/blog-post.component';
import { HomeComponent } from './home-module/home/home.component';
import { AppCustomPreloader } from './app-custom-preloading';
import { Help } from './help/help.component';

export const routesApp: Routes = [
  { path: '',pathMatch: 'full',redirectTo: 'home' },{
    path: 'home',component: HomeComponent
  },//{
  //  path: 'main',//  component: AppComponent
  //},{
    path: 'callback',component: CallbackComponent
  },{
    path: 'place/:id',loadChildren: './place-module/place.module#PlaceModule',data: { preload: false }
  },{
    path: 'login',loadChildren: './authentication-module/authentication.module#AuthenticationModule',data: { preload: true }
  },{
    path: 'place-account',loadChildren: './place-account-module/place-account.module#PlaceAccountModule'
  },{
    path: 'reports',loadChildren: './report-module/report.module#ReportModule'
  },{
    path: 'new-place',loadChildren: './new-place-module/new-place.module#NewPlaceModule',{
    path: 'mybooking',loadChildren: './place-booking-module/place-booking.module#PlaceBookingModule'
  },{
    path: 'user-booking',loadChildren: './user-booking-module/user-booking.module#UserBookingModule',{
    path: 'my-account',loadChildren: './user-account-module/user-account.module#UserAccountModule'
  },{
    path: 'blog',component: BlogComponent
  },{
    path: 'blog-post/:id',component: BlogPostComponent
  },{
    path: 'place-creditandnotify',loadChildren: './place-credit-and-notification-module/place-credit-and-notification.module#PlaceCreditAndNotificationModule'
  },{
    path: 'about',component: About
  },{
    path: 'help',component: Help
  },{
    component: PageNotFoundComponent,path: "404",},{
    path: "**",redirectTo: '404'
  }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(routesApp,{
  preloadingStrategy: AppCustomPreloader
});

home.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import { homerouting } from './home.routing';

import {
  MatFormFieldModule,MatInputModule,MatSlidetoggleModule
} from '@angular/material';
import { MapLoaderModule } from '../loaders/map/map-loader.module';
import { HomeComponent } from './home/home.component';
import { PlaceListComponent } from './home/place-list/place-list.component';
import { PlaceBoxComponent } from './home/place-Box/place-Box.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { RouterModule } from '@angular/router';


@NgModule({
  exports: [
    MatFormFieldModule,MatSliderModule
  ]
})
export class MaterialAngularModules { }

@NgModule({
  entryComponents: [],imports: [
    CommonModule,homerouting,NgbModule
  ],declarations: [
    HomeComponent,PlaceListComponent,PlaceBoxComponent
  ],exports: [
    HomeComponent
  ]
})

export class HomeModule { }

app.component.html

<!--<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Titillium+Web&display=swap" rel="stylesheet">-->
<!--  -->

<div class="router-container noScroll" >

  

  <mat-sidenav-container class="example-sidenav-container">

    <mat-sidenav #snav>

      <!-- <p id="nameAuth" *ngIf="authService.isLoggedIn()">{{authService.getName()}}</p>
  <div *ngIf="authService.isLoggedIn()" class="nameAuth">{{authService.getName()}}</div>
        -->
      <p class="menu-boton"><button (click)="snav.close()" routerLink="/home" mat-button  [ngClass]="(document.location.pathname=='/home')?'button-left-panel': 'button-left-panel-noactive'">Home</button></p>
      <p class="menu-boton"><button (click)="snav.close()" routerLink="/about" mat-button  [ngClass]="(document.location.pathname=='/about')?'button-left-panel': 'button-left-panel-noactive'">Nosotros</button></p>
      <p class="menu-boton"><button (click)="snav.close()" routerLink="/blog" mat-button  [ngClass]="(document.location.pathname=='/blog')?'button-left-panel': 'button-left-panel-noactive'">Blog</button></p>
      <p class="menu-boton"><button (click)="snav.close()" routerLink="/ayuda" mat-button [ngClass]="(document.location.pathname=='/ayuda')?'button-left-panel': 'button-left-panel-noactive'">Ayuda</button></p>



      <div *ngIf="authService.isLoggedIn() && hasPlace">
        <mat-divider></mat-divider>
        <p class="menu-boton">Mi Negocio</p>
        <p class="menu-boton"><button (click)="snav.close()" routerLink="/place-account" mat-button  [ngClass]="(document.location.pathname=='/place-account')?'button-left-panel': 'button-left-panel-noactive'">Mi Lugar</button></p>
        <p class="menu-boton"><button (click)="snav.close()" routerLink="/mybooking" mat-button  [ngClass]="(document.location.pathname=='/mybooking')?'button-left-panel': 'button-left-panel-noactive'">Mi Calendario</button></p>
        <p class="menu-boton"><button (click)="snav.close()" routerLink="/place-creditandnotify" mat-button  [ngClass]="(document.location.pathname=='/place-creditandnotify')?'button-left-panel': 'button-left-panel-noactive'">Creditos</button></p>
        <p class="menu-boton"><button (click)="snav.close()" routerLink="/reports" mat-button  [ngClass]="(document.location.pathname=='/reports')?'button-left-panel': 'button-left-panel-noactive'">Reportes</button></p>
      </div>

      <div>
        <p class="menu-boton"><button (click)="snav.close()" *ngIf="!authService.isLoggedIn()" routerLink="/login" mat-button [ngClass]="(document.location.pathname=='/login')?'button-left-panel': 'button-left-panel-noactive'">Iniciar sesion</button></p>
      </div>

      <div *ngIf="authService.isLoggedIn()">
        <mat-divider></mat-divider>
        <a style="margin-top:30px;" class="header-menu">
          <div class="user-picture-url" style="cursor: pointer;">
            <img style="width:35px;height:35px;" [src]="userProfileImage != null ? userProfileImage : ''" alt="">
            {{name}}
            <div class="header-menu" (click)="modal.show(); snav.close()" (mouseclick)="modal.show()">
              <mat-icon [matBadge]="unreadMessages" matBadgeColor="warn">notifications</mat-icon>
            </div>
          </div>
        </a>

        <p class="menu-boton"><button (click)="snav.close()" routerLink="/my-account" mat-button [ngClass]="(document.location.pathname=='/my-account')?'button-left-panel': 'button-left-panel-noactive'">Mi Cuenta</button></p>
        <p class="menu-boton"><button (click)="snav.close()" routerLink="/user-booking" [ngClass]="(document.location.pathname=='/user-booking')?'button-left-panel': 'button-left-panel-noactive'" mat-button>Mis reservas</button></p>
        <p class="menu-boton"><button (click)="authService.logout()" mat-button>Log Out</button></p>

      </div>

      <div *ngIf="authService.isLoggedIn() && !hasPlace">
        <mat-divider></mat-divider>
        <p class="menu-boton"><button (click)="snav.close()" style="margin-top:25px; padding-left:20px;padding-right:20px;" routerLink="/new-place" mat-button [ngClass]="(document.location.pathname=='/new-place')?'button-left-panel': 'button-left-panel-noactive'">Agrega tu espacio</button></p>
      </div>

    </mat-sidenav>

    <mat-sidenav-content>
      <mat-toolbar color="primary" class="example-toolbar">
        <img routerLink="/home" style="outline: none; border: 0; cursor: pointer;" [src]="fullImagePath" class="img-logo">

        <ul class="menu-upi">

          <li><a class="header-menu" routerLink="/home">Home</a></li>
          <li><a class="header-menu" routerLink="/about">Nosotros</a></li>
          <li><a class="header-menu" [routerLink]="['/blog']" routerLinkActive="active">Blog</a></li>
          <li><a class="header-menu" routerLink="/help">Ayuda</a></li>

        </ul>

        <!--
    <form class="search-form">
      <mat-form-field class="search-width">
        <input matInput placeholder="Find a place" [formControl]="searchFormControl">
        <mat-error *ngIf="searchFormControl.hasError('email') && !searchFormControl.hasError('required')">
          Please enter a valid email address
        </mat-error>
      </mat-form-field>
    </form>
     -->
        <!--<a *ngIf="!authService.isLoggedIn()" (click)="authService.login()">Log In</a>-->

        <div class="header-widget">
          <!--<a (click)="login()" class="header-menu popup-with-zoom-anim">google</a>
      <a (click)="authService.signup('venturinosaporta@gmail.com','Ventuu3040')" class="header-menu popup-with-zoom-anim">Registrarse</a>-->
          <!--<a *ngIf="!authService.isLoggedIn()" (click)="authService.login()" class="header-menu popup-with-zoom-anim">Iniciar sesion</a>-->
          <p class="menu-usuario">
            <img *ngIf="!userHasLoaded && !error" [src]="loadingImagePath" style="width:15%; float:right" />
          </p>
          <ul class="menu-usuario" *ngIf="userHasLoaded && !error">
            <li *ngIf="authService.isLoggedIn() && hasPlace">
              <a class="header-menu" style="cursor: pointer;" [matMenuTriggerFor]="menuempresa">Mi negocio</a>
              <mat-menu #menuempresa="matMenu" [overlapTrigger]="false">
                <p class="menu-boton"><button routerLink="/place-account" mat-button [ngClass]="{'button-left-panel': router.url=='/place-account'}" >Mi Lugar</button></p>
                <p class="menu-boton"><button [routerLink]="['/mybooking']" mat-button>Mi Calendario</button></p>
                <p class="menu-boton"><button routerLink="/place-creditandnotify" mat-button>Creditos</button></p>
                <p class="menu-boton"><button routerLink="/reports" mat-button>Reportes</button></p>
              </mat-menu>
            </li>
            <li *ngIf="authService.isLoggedIn()">

              <a style="margin-top:30px;" class="header-menu" [matMenuTriggerFor]="menuuser">
                <div class="user-picture-url" style="cursor: pointer;">
                  <img style="width:35px;height:35px;" [src]="userProfileImage != null ? userProfileImage : ''" alt="">
                  {{name}}
                </div>
              </a>

              <mat-menu #menuuser="matMenu" [overlapTrigger]="false">
                <p class="menu-boton"><button routerLink="/my-account"  *ngIf="authService.isLoggedIn()" mat-button>Mi Cuenta</button></p>
                <p class="menu-boton"><button routerLink="/user-booking" *ngIf="authService.isLoggedIn()" mat-button>Mis Reservas</button></p>
                <p class="menu-boton"><button *ngIf="authService.isLoggedIn()" mat-button (click)="authService.logout()">Log Out</button></p>
              </mat-menu>
            </li>
            <li *ngIf="authService.isLoggedIn()">
              <div class="header-menu" style="cursor: pointer;" (click)="modal.show()" (mouseclick)="modal.show()">
                <mat-icon [matBadge]="unreadMessages" matBadgeColor="warn">notifications</mat-icon>
                <!-- Include text description of the icon's meaning for screen-readers -->

              </div>
            </li>

            <li>
              <a class="header-menu" *ngIf="!authService.isLoggedIn()" routerLink="/login">Iniciar sesion</a>
            </li>
            <li>
              <label class="header-menu popup-with-zoom-anim" *ngIf="authService.isLoggedIn() && mobileQuery.matches">{{authService.getName()}}</label>
              <a *ngIf="authService.isLoggedIn() && !hasPlace" style="margin-top:25px; padding-left:20px;padding-right:20px;" routerLink="/new-place" class="button border header-menu">Agrega tu espacio </a>
            </li>

          </ul>
          <div *ngIf="error" style="color: black; text-align: right; margin-top: 15px">
            <button (click)="window.location.reload()">
              <span class="material-icons">
                loop
              </span>
              Refrescar
            </button>
          </div>
        </div>


        <button class="menu-mobile" mat-icon-button (click)="snav.toggle()"><mat-icon>menu</mat-icon></button>

      </mat-toolbar>
      <div [hidden]="!loadingModule" style="position:fixed; margin-top:25%; margin-left: 50%;">
        <h2>Loading...</h2>
        <mat-progress-bar mode="indeterminate"></mat-progress-bar>
      </div>
      <div [hidden]="loadingModule" >
        <router-outlet></router-outlet>
      </div>
    </mat-sidenav-content>
  </mat-sidenav-container>
</div>

<toaster-container [toasterconfig]="config"></toaster-container>

<app-bell-notify #modal style="cursor: pointer;" (numberOfNotificationsEmiter)="getNumberOfNotificationsUnread($event)">
  <div class="app-modal-header">
    Notificaciones
  </div>
  <div class="app-modal-body">
    Whatever content you like,form fields,anything
  </div>
  <div class="app-modal-footer">
    <button type="button" class="simple-button" (click)="modal.hide()">Close</button>
  </div>
</app-bell-notify>

MapLoaderModule

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { browserModule } from "@angular/platform-browser";
import { MapComponent } from "src/app/map/map.component";
import { AgmCoreModule,GoogleMapsAPIWrapper } from '@agm/core';
import { AgmSnazzyInfoWindowModule } from '@agm/snazzy-info-window';
import { AgmJsMarkerClustererModule } from '@agm/js-marker-clusterer';
import { RouterModule } from '@angular/router';


@NgModule({
  imports: [
    CommonModule,AgmCoreModule.forRoot({ apiKey: 'AIzaSyB23x4UGHNZ-YRDCM1rI-AcdQ6lTyQcdyo' }),AgmJsMarkerClustererModule,AgmSnazzyInfoWindowModule,RouterModule
  ],exports: [MapComponent],declarations: [MapComponent],providers: [GoogleMapsAPIWrapper]
})
export class MapLoaderModule {}

解决方法

删除routerLink上的/

routerLink='home'其余相同

,

在 MapLoaderModule 中缺少导入 RouterModule

const mapRoutes: Routes = [
];

export const maprouting: ModuleWithProviders = RouterModule.forChild(mapRoutes);

我不需要在这个模块中路由,所以我留空