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

Angular2 importing component methods into another component

我有一个 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();
  }

}    

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

话虽如此,理想情况下,要检查 用户是否已登录 状态,您应该调用服务。

该服务应该告诉用户是否已登录,并且它应该在服务上有一个静态方法。