Angular2将组件方法导入另一个组件

时间:2016-05-15 21:20:20

标签: javascript angularjs angular auth0

我有一个home组件需要调用LoginComponent方法isLoggedIn()来检查用户是否在@CanActivate中以如下方式登录

只有在用户登录并进行身份验证时才应激活主组件

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

}    

1 个答案:

答案 0 :(得分:2)

loggedIn方法不是static方法,因此不会被调用,

理想情况下,要检查用户登录状态是否应该调用服务。

该服务应告知用户是否已登录,并且该服务还应具有静态方法。

希望这会有所帮助!!