gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:27:02 25 4
gpt4 key购买 nike

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

只有当用户登录并通过身份验证时,home 组件才会激活

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

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

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

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

关于javascript - Angular2将组件方法导入另一个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37243795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com