2016-10-31 4 views
0

я пытаюсь добиться следующего:Угловые 2 маршрутизаторы не работает, как ожидалось

  • логины пользователей затем попадаю к компоненту сайта (Первая страница по умолчанию после входа в систему) и я хранить пользователя конфигурации т.е. которые все компоненты пользователь может получить доступ к локальному Хранение или хранение сеанса.

  • Если пользователь пытается напрямую получить доступ к компоненту/сайту без ведения журнала , тогда пользователь должен быть перенаправлен на страницу входа.

Проблема: Выше функциональность работает очень хорошо, но: Если я пытаюсь доступа/сайт в качестве первой страницы, то угловой маршрутизатор перенаправляет меня/Логин, но после входа в систему, он не перенаправляет меня на сайте снова. Я ожидаю, что после входа в систему он снова перенаправит меня на компонент сайта.

Шаги, которые:

  1. Открыть новую вкладку/Window (так что мы не имеем никакой конфигурации в локальной или сеанса хранения).

  2. Попробуйте получить доступ/сайт, вы должны автоматически перенаправляться в компонент/login.

  3. После/login он должен снова перенаправляться на сайт (его не работает).

Войти Компонент:

@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: т.с.

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

UPDATE

Как предложили ответ, я адаптировал код:

компонент сайта состоит из подкомпонент GeneralComponent и который состоит из компонента клиента и счетов-фактуры Компонент.

Они не отображаются, если сайт был перенаправлен после входа в систему.

сайта .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

Я делаю это аналогичным образом. Я просто использую

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

Это работает для меня.

Так изменить

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

в LoginComponent к вышесказанному, и она должна работать, как ожидалось.

+0

Ну перенаправление работает, но теперь компоненты не отображаются должным образом, проверьте мой раздел обновления в коде. – Roxy

+0

Не могли бы вы предоставить jsfiddle? Было бы гораздо легче найти проблему. –

+0

https://jsfiddle.net/hgz1obd2/2/#&togetherjs=g7xQKulfu0 – Roxy

Смежные вопросы