【发布时间】:2017-01-17 09:24:14
【问题描述】:
在 Angular2 中传递实例方法。
在以下代码中从模板调用login() 时,出现此错误:
Failure TypeError: Cannot read property 'router' of null
at AuthLoginComponent.success (auth-login.component.ts:30)
at ZoneDelegate.invoke (zone.js:242)
at Object.onInvoke (core.umd.js:4391)
at ZoneDelegate.invoke (zone.js:241)
at Zone.run (zone.js:113)
at zone.js:520
at ZoneDelegate.invokeTask (zone.js:275)
at Object.onInvokeTask (core.umd.js:4382)
at ZoneDelegate.invokeTask (zone.js:274)
at Zone.runTask (zone.js:151)
at drainMicroTaskQueue (zone.js:418)
at XMLHttpRequest.ZoneTask.invoke (zone.js:349)
在以下代码中:
@Component({
moduleId: module.id,
selector: "app-auth-login",
templateUrl: "/app/components/auth/login/auth-login.component.html"
})
export class AuthLoginComponent implements OnInit {
username : "";
password : "";
constructor(
private authLoginService: AuthLoginService,
private router: Router
) {}
ngOnInit(): void {
}
success(value: Response) : void {
console.log("Success", value);
this.router.navigate(["/home"]);
}
failure(value: Response) : void {
console.log("Failure", value);
}
login() : void {
this.authLoginService.login(
this.username,
this.password,
this.success,
this.failure
)
}
}
我尝试传递this 和success,然后在服务中调用t[success](),但这会产生完全相同的错误。
我的服务使用断路器模式实现了客户端“负载平衡器”,这就是我传递成功/失败函数以尽可能重用我的代码的原因。
该服务正在使用 rxjs 和 toPromise,例如
httpService(...).toPromise().then(success).catch(response => {(circuit breaker pattern on some failures)})
【问题讨论】:
-
你需要通过
res => this.success(res)
标签: angular typescript angular2-routing angular2-services