Angular 2路由器未按预期工作

时间:2016-10-31 08:09:20

标签: angular

我正在努力实现以下目标:

  • 用户登录然后被重定向到站点组件(登录后的第一个默认页面)并且我存储用户 所有组件用户都可以在本地访问的配置 存储或会话存储。

  • 如果用户尝试直接访问/ site组件而不进行日志记录 在,然后应将用户重定向到登录页面。

问题:以上功能运行良好但是: 如果我尝试访问/ site作为第一页,那么angular router会将我重定向到/ login但是在登录后,它不会再将我重定向到站点。我希望在登录后它应该再次将我重定向到站点组件。

涉及的步骤:

  1. 打开新标签/窗口(以便我们在本地或会话存储中没有任何配置)。

  2. 尝试访问/ site,您应该自动重定向到/ login组件。

  3. 在/ login之后,它应该再次重定向到/ site(它不能正常工作)。

  4. 登录组件:

    @Component({
        selector: 'login',
        templateUrl: './login.component.html',
        styleUrls: ['./login.component.css']
    })
    
    @NgModule({
    providers:[AuthenticationService]
    })
    export class LoginComponent implements OnInit {
        public user: User;
        public isUserAuthenticated = false;
        // For testing we are going to use Dummy Configuration.
        // Actual data will come from Rest Service
    
    
        private dummyConfiguration:Object={
            "user":"dummy",
            "component":[{
                      "name":"CustomerComponent",
                      "access":"ENABLED"
            },
            {
                  "name":"InvoicingComponent",
                      "access":"HIDDEN"
    
            }
    
            ]
        };
    
        constructor(private router: Router,private authenticationService : AuthenticationService) {
            this.user = new User();
        }
    
        login() {
            this.isUserAuthenticated = true;
            this.authenticationService.saveInSession(this.dummyConfiguration);
            this.router.navigate(['/site', {}]);
        }
    
        ngOnInit() {
        }
    }
    
    export class User {
        public email: string;
        public password: string;
    }
    

    SiteComponent

    @Component({
      selector: 'site',
      templateUrl: './site.component.html',
      styleUrls: ['./site.component.css']
    })
    export class SiteComponent extends SuperParentComponent{
      constructor(private router: Router, private authenticationService: AuthenticationService) { 
        super();
        this.validateSession(router,authenticationService);
      }
    }
    

    SuperParentComponent

    export class SuperParentComponent {
    
    constructor(){    
    }
        validateSession( router: Router,  authenticationService: AuthenticationService) {
            if (!authenticationService.isUserLoggedIn()) {
                router.navigate(['/login', {}]);
            }
        }
    }
    

    的AuthenticationService:TS

    export class AuthenticationService {
    
    
            @SessionStorage() public userConfiguration: Object;
    
            isAuthentic(component: string):boolean {
                if (this.isComponentAllowed(component)){
                    return true;
                }
            }
    
            public getUserConfiguration():Object {
                return this.userConfiguration;
            }
    
            saveInSession(data: Object) {
                this.userConfiguration = data;
            }
    
            isUserLoggedIn():boolean{
                if(this.userConfiguration==null){
                    return false;
                }
                return true;
            }
    
            isComponentAllowed(component:string){
               var result:Array<Object>;
               if(this.userConfiguration=={}){
                   return false;
               }
               if(this.userConfiguration.hasOwnProperty("component")){
                   result=this.userConfiguration["component"];
                   for (var i = 0; i < result.length; i++) {
                       var currentComponent:Object=result[i];
                    if (currentComponent["name"] ==component && currentComponent["access"]== AccessType.ENABLED) {
                         return true;
                    }
               }
            }
            return false;
    
    
        }
    
        }
    
         enum AccessType {
             ENABLED=<any>"ENABLED",
             HIDDEN=<any>"HIDDEN"
    
    
         }
    

    如果用户可以访问给定组件,则此用户配置仅用于授权。我会从服务器上获得它。

    以下是我的完整代码:https://github.com/tsingh38/Angular2.git

    更新

    根据建议的答案,我修改了代码:

    站点组件由子组件GeneralComponent组成,它由Customer Component和Invoice Component组成。

    如果在登录后重定向网站,则不会显示它们。

    网站.html

    <div style="width: 100%;">
       <div style="float:left; width: 20%">
           <navigation></navigation>
       </div>
       <div style="float:right;">
           <general></general>
       </div>
    </div>
    <div style="clear:both"></div>
    

    General.Component.html

    <div style="border:1px solid black;">
        <customer></customer></div>
    <div style="border:1px solid blue;float:bottom">
    <invoice></invoice>
    </div>
    

    Customer.html

    <div *ngIf="allowed">This is customer data</div>
    <div *ngIf!="allowed"></div>
    

    Invoice.html

    <div *ngIf="allowed">This is invoice data</div>
    <div *ngIf!="allowed"></div>
    

    客户组件

    @Component({
      selector: 'customer',
      templateUrl: './customer.component.html',
      styleUrls: ['./customer.component.css'],
      providers:[AuthenticationService]
    })
    export class CustomerComponent extends SuperChildComponent{
      private authenticationService:AuthenticationService;
      constructor(authenticationService : AuthenticationService) {
        super(authenticationService);
        this.authenticationService=authenticationService;
         this.isAllowed(this.constructor.name);
      }
    
    
    
    }
    

    SuperChildComponent

    export class SuperChildComponent {
        public allowed: boolean = false;
        private superAuthenticationService:AuthenticationService;
    
    
        constructor(authenticationService: AuthenticationService) {
            this.superAuthenticationService = authenticationService;
        }
    
        isAllowed(component: string) {
            this.allowed = this.superAuthenticationService.isAuthentic(component);
        }
    
    }
    

    感谢。

1 个答案:

答案 0 :(得分:1)

我的做法与此类似。我只是用

this.router.navigate(['/site']);

这对我有用。

所以改变你的

this.router.navigate(['/site', {}]);

在LoginComponent中,它应该按预期工作。