簡體   English   中英

Angular 2從CanActivate服務導航到根目錄

[英]Angular 2 navigate to root from CanActivate service

嗨,我有一個奇怪的問題,不知道如何解決。 因此,我有服務來檢查您是否在訪問Web應用程序中的某些URL時登錄。 如果不是,它將重定向到主頁。

我的服務

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

@Injectable()
export class AuthService  implements CanActivate {
    private userLogedin: string = localStorage.getItem('AUTHENTICATION');

    constructor(private router: Router) {}

    canActivate() {
        if(this.userLogedin === 'true') {
            return true;
        }

        this.router.navigateByUrl('/');
        return false;
    }
}

我的模塊路由

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

import { LandingPageComponent } from 'app/components/LandingPageComponent/LandingPageComponent';

const landingPageRoutes: Routes = [
    {path: '', component: LandingPageComponent, pathMatch: 'full'}

    ];

export const landingPageRouting: ModuleWithProviders = RouterModule.forChild(landingPageRoutes);

路由器可以激活模塊路由

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

import { ProfilePageComponent } from 'app/components/ProfilePageComponent/ProfilePageComponent';
import { AuthService } from 'app/shared/AuthService';


const profilePageRoutes: Routes = [
    {path: 'profile', component: ProfilePageComponent, canActivate: [AuthService]  }
    ];

export const profilePageRouting: ModuleWithProviders = RouterModule.forChild(profilePageRoutes);

但是,當您重定向到主頁時,它給了我一個空白頁。

因此,如果您有此問題,請嘗試使用RouterModule.forRoot(appRoutes,{useHash:true})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM