Angular 2 从 CanActivate 服务导航到根目录

标签 angular typescript routing canactivate

嗨,我有一个奇怪的问题,不知道如何解决。所以我有服务检查你是否在访问网络应用程序中的某个 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);

路由器可以激活module.routing

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);

但是当 hi 重定向到主页时,它给了我一个空白页面。

最佳答案

所以如果你有这个问题试试这个 RouterModule.forRoot(appRoutes, { useHash: true })

关于Angular 2 从 CanActivate 服务导航到根目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42655919/

相关文章:

javascript - 响应式(Reactive)表单验证不起作用

typescript - 通过追加到 SQLite 上的现有数组来更新 Sequelize 列

asp.net - ASP.net上的URL路由,需要从url中获取参数

file-upload - Angular 2 : ng2-file-upload : cannot load it correctly using SystemJS

node.js - 删除 API 不起作用

css - 使用 CSS 引导行中的动态列

来自无类型对象的 Typescript 索引类型

ASP.NET 路由 - 从数据库加载路由?

c# - Asp.net MVC 路由不匹配某些文件扩展名

javascript - 无法在 Google Pay TEST 环境和订单总额中添加测试卡