Angular 2:TypeError:不是函数
问题描述:
我正在使用angular-cli RC0搭建Angular 2应用程序。 我已经设置了一个AuthGuard来保护一些路线。这名警卫实施了CanActivate,如果没有登录,则将用户重定向到登录页面,并且一个Angular Material2 MdSbackBar应该显示一条自定义消息。 这里AuthGuard:Angular 2:TypeError:不是函数
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private authService: AuthService,
private growlerService: GrowlerService
) { }
canActivate(): boolean {
if (this.authService.isAuthenticated()) {
return true;
} else {
this.router.navigate(['auth/login']);
this.growlerService.growl('Autenticazione richiesta', GrowlerMessageType.Error);
return false;
}
}
}
在这里,如上所示,其被称为在CanActivate方法咆哮服务:
@Injectable()
export class GrowlerService {
constructor() { }
growl: (message: string, type: GrowlerMessageType) => void;
}
最后在咆哮部件的实际功能
export class GrowlerComponent {
constructor(
private snackBar: MdSnackBar,
private growlerService: GrowlerService
) {
growlerService.growl = this.growl.bind(this);
}
growl(message: string, type: GrowlerMessageType): void {
const growlerConfig = new MdSnackBarConfig();
growlerConfig.duration = 3000;
growlerConfig.extraClasses = this.growlerTypeClass(type);
this.snackBar.open(message, null, growlerConfig);
}
}
当CanActivate未被调用时,所有内容都正确地导入/导出,并且咆哮者可以正常工作。为了构建这个,我遵循this example,在示例中用一个角度材料组件替换了增量器组件。 GrowlerTypeClass是在扩展器组件中定义的私有方法,但这不是问题。 问题是,当未登录的用户和canActivate尝试调用咆哮服务,我得到以下错误控制台:提前
EXCEPTION: Uncaught (in promise): TypeError: this.growlerService.growl is not a function
TypeError: this.growlerService.growl is not a function
at AuthGuard.webpackJsonp.259.AuthGuard.canActivate
感谢您帮助。
答
在GrowlerComponent中,您自己定义了growlerService.growl函数。它看起来像是通过设计(咆哮者的图书馆),以实现某种类型的咆哮者特定的回调机制。但是你的AuthGuard没有这个功能。它看起来像你可能想要添加: growlerService.growl = this.growl.bind(this);
...以及AuthGuard构造函数。然后实现该方法(类似于GrowlerComponent)。
你可以添加Auth Guard的构造函数吗? – echonax
@echonax我已经编辑了片段。对不起,我的英语很糟糕:( – bado