#angular6
#angular6
Вопрос:
В моем основном маршруте у меня много модулей, некоторые загружаются лениво, другие — стратегия предварительной загрузки, также у меня есть маршруты для простых компонентов. Некоторые маршруты имеют AuthGuard.
Когда я нажимаю на элемент с Routerlink, он переходит в Authguard, но там останавливается, представление не загружается, и URL-адрес не меняется.
Если я введу маршрут в 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,
MatFormFieldModule,
MatExpansionModule,
MatDividerModule,
MatTableModule,
MatButtonModule,
MatMenuModule,
MatSelectModule,
MatSidenavModule,
MatIconModule,
MatToolbarModule,
MatToolbarModule,
MatCheckboxModule,
MatButtonToggleModule,
MatTabsModule,
MatPaginatorModule,
MatDialogModule,
MatAutocompleteModule,
MatNativeDateModule,
MatProgressSpinnerModule,
MatListModule,
MatSliderModule,
MatProgressBarModule,
MatSlideToggleModule,
MatStepperModule,
MatRadioModule,
MatCardModule,
MatBadgeModule
]
})
export class MaterialAngularModules { }
@NgModule({
declarations: [
AppComponent,
DisableControlDirective,
CallbackComponent,
GenericModal,
PageNotFoundComponent,
About,
Help,
ConfirmationDialog,
BlogComponent,
BlogPostComponent,
BellNotifyComponent,
OnScrollLoadComponent,
DialogTermsAndCondOverview
],
entryComponents: [GenericModal, ConfirmationDialog, DialogTermsAndCondOverview],
imports: [
BrowserModule,
BrowserAnimationsModule,
MaterialAngularModules,
HttpClientModule,
CommonModule,
FormsModule,
RouterModule,
ReactiveFormsModule,
MatCheckboxModule,
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, RouterModule, 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',
data: { preload: true }
},
{
path: 'mybooking',
loadChildren: './place-booking-module/place-booking.module#PlaceBookingModule'
},
{
path: 'user-booking',
loadChildren: './user-booking-module/user-booking.module#UserBookingModule',
data: { preload: true }
},
{
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, MatTabsModule, MatInputModule, MatIconModule, MatAutocompleteModule, MatSelectModule,
MatCheckboxModule, MatButtonToggleModule, MatSliderModule, 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, MatTabsModule, MatInputModule, MatIconModule, MatAutocompleteModule, MatSelectModule,
MatCheckboxModule, MatButtonToggleModule, MatSlideToggleModule, MatSliderModule
]
})
export class MaterialAngularModules { }
@NgModule({
entryComponents: [],
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
MaterialAngularModules,
homerouting,
MapLoaderModule,
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 Webamp;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() amp;amp; 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() amp;amp; !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') amp;amp; !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 amp;amp; !error" [src]="loadingImagePath" style="width:15%; float:right" />
</p>
<ul class="menu-usuario" *ngIf="userHasLoaded amp;amp; !error">
<li *ngIf="authService.isLoggedIn() amp;amp; 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() amp;amp; mobileQuery.matches">{{authService.getName()}}</label>
<a *ngIf="authService.isLoggedIn() amp;amp; !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 {}
Комментарии:
1. Вы добавили in
app-routing.module.ts
в массив imports@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] })
перед экспортом классаAppRoutingModule
? и<router-outlet></router-outlet>
в app.component.html ?2. Обновите ссылки вашего маршрутизатора этим. надеюсь, что это будет работать нормально
<li> <a class="header-menu" [routerLink] = "['/home']" >HOME</a> </li>
3. Да, я импортировал подобные маршруты, и у меня есть router-outlet в app.component
4. Вы обновили свои routerLink’ы?
5. обратный вызов находится в другом модуле, поэтому его нет в app.component. Я попытаюсь воспроизвести это в stackblitz! Спасибо
Ответ №1:
Удалите / on routerLink
routerLink='home'
то же самое для остальных
Комментарии:
1. Привет. Я получил такое же поведение. Он отправляется в authguard с правильным «state.url», а затем ничего не происходит.
2. попробуйте отредактировать свой пост, чтобы показать нам полный код, а не изображения
3. Привет, я обновил код. Я пробовал использовать разные форматы routerlink, такие как [routerLink] =»[‘/mybooking’]». Опять же, когда я нажимаю на один из них, он переходит к authguard с правильным маршрутом, но затем останавливается. В AuthGuard я ввел «return true» в поле «canActivate»… Также я получаю такое же поведение с routerlink для простых компонентов без AuthGuard…
4. У вас дома.модули объявляются при импорте routesApp и HomeComponent в объявлениях. Также удалите / из routerLink в HTML (я всегда использовал без /)
Ответ №2:
Отсутствовал импорт RouterModule в MapLoaderModule
const mapRoutes: Routes = [
];
export const maprouting: ModuleWithProviders = RouterModule.forChild(mapRoutes);
Мне не нужно маршрутизировать в этом модуле, поэтому я оставляю пустым