简体   繁体   English

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

[英]Angular2 importing component methods into another component

I have a home component which needs to call LoginComponent method isLoggedIn() to check if the user is logged in as follows in @CanActivate我有一个 home 组件需要调用 LoginComponent 方法 isLoggedIn() 来检查用户是否在 @CanActivate 中如下登录

The home component should activate only if the user is logged in and authenticated仅当用户登录并通过身份验证时才应激活 home 组件

HomeComponent.ts 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登录组件.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, loggedIn方法不是static方法,因此不会被调用,

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.该服务应该告诉用户是否已登录,并且它应该在该服务上有一个静态方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM