I have a home component which needs to call LoginComponent method isLoggedIn() to check if the user is logged in as follows in @CanActivate
The home component should activate only if the user is logged in and authenticated
HomeComponent.ts
import {Component, OnInit} from 'angular2/core';
import {AboutComponent} from "../about/AboutComponent";
import {ROUTER_DIRECTIVES} from "angular2/router";
import {LoginComponent} from '../login/LoginComponent'
@Component({
selector: 'home',
/* template: `
<div>
<div class="input">
<label for="Name">Name</label>
<input type="text" id="name" #name>
</div>
<button (click)="onGetAll(name.value)">GET Request
</button>
<p>Response: {{response}}</p>
</div>
<a [routerLink]="['../About']">link to About component</a>
`,*/
templateUrl: '../app/templates/dashboard.html',
styleUrls: ['../app/assets/light-bootstrap-dashboard.css','../app/assets/demo.css','../app/assets/pe-icon-7-stroke. css','../app/assets/bootstrap.min.css'],
directives : [ROUTER_DIRECTIVES]
})
@CanActivate(() => LoginComponent.loggedIn()) //<-- This is not working
export class HomeComponent implements OnInit {
response: string;
constructor() {}
ngOnInit() {}
onGetAll(name: string){
console.log("Button clicked.. more code goes here " + name);
}
}
LoginCompoent.ts
import {Component} from 'angular2/core';
import {Router, RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {AuthHttp,AuthConfig, tokenNotExpired, AUTH_PROVIDERS} from 'angular2-jwt';
import {HomeComponent} from '../home/HomeComponent'
import {AboutComponent} from '../about/AboutComponent'
import {AuthService} from '../../services/AuthService'
declare var Auth0Lock;
@Component({
selector: 'protected',
template: '<router-outlet></router-outlet>',
directives: [ROUTER_DIRECTIVES],
providers: [AUTH_PROVIDERS,AuthService]
})
export class LoginComponent {
constructor(private auth: AuthService) {
this.auth.login();
}
login() {
this.auth.login();
}
logout() {
this.auth.logout();
}
loggedIn() {
return tokenNotExpired();
}
}
loggedIn
method is not a static
method hence it will not be called,
Having said that, ideally, to check whether the user logged-in state you should call a service.
The service should tell if the user is logged-in and also it should have a static method on the service.