使用Angular 2可以激活; TS很好,但我收到了一个错误

时间:2017-01-15 09:35:37

标签: angular angular2-routing

我是Angular 2的新手,试图保护新应用中的路线。使用的东西似乎是Can Activate,但即使使用最简单的can激活示例也似乎打破了角度。我收到以下错误:

ZoneAwareError message:
"Uncaught (in promise): TypeError: Cannot set property 'stack' of undefined
TypeError: Cannot set property 'stack' of undefined
at NoProviderError.set [as stack] (http://localhost:4200/vendor.bundle.js:6147:61)
at assignAll (http://localhost:4200/vendor.bundle.js:98482:29)
at NoProviderError.ZoneAwareError (http://localhost:4200/vendor.bundle.js:98553:16)
at NoProviderError.BaseError [as constructor] (http://localhost:4200/vendor.bundle.js:6109:16)
at NoProviderError.AbstractProviderError [as constructor] (http://localhost:4200/vendor.bundle.js:58855:16)
at new NoProviderError (http://localhost:4200/vendor.bundle.js:58904:16)
at ReflectiveInjector_._throwOrNull (http://localhost:4200/vendor.bundle.js:80617:19)
at ReflectiveInjector_._getByKeyDefault (http://localhost:4200/vendor.bundle.js:80654:25)
at ReflectiveInjector_._getByKey (http://localhost:4200/vendor.bundle.js:80604:25)
at ReflectiveInjector_.get (http://localhost:4200/vendor.bundle.js:80366:21)
at AppModuleInjector.NgModuleInjector.get (http://localhost:4200/vendor.bundle.js:59758:52)
at PreActivation.getToken (http://localhost:4200/vendor.bundle.js:24841:25)
at MapSubscriber.project (http://localhost:4200/vendor.bundle.js:24737:48)
at MapSubscriber._next (http://localhost:4200/vendor.bundle.js:11337:35)
at MapSubscriber.Subscriber.next (http://localhost:4200/vendor.bundle.js:6655:18)

我的代码如下。

可以激活:

import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';

@Injectable()
export class CanActivateAuthGuard implements CanActivate {

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return false;
  }
}

路由模块:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { ThoughtListComponent } from './thoughts/thought-list.component';
import { LoginComponent } from './login/login.component';

import { CanActivateAuthGuard } from './can-activate.service';

const routes: Routes = [
    { path: '', pathMatch: 'full', redirectTo: 'thoughtList' },
    { path: 'login', component: LoginComponent },
    { path: 'thoughtList',
      component: ThoughtListComponent,
      canActivate: [CanActivateAuthGuard]
    }
]
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {}

export const routableComponents = [
    ThoughtListComponent,
    LoginComponent
];

由于我正在使用TypeScript,我知道canActivate应该能够返回一个简单的布尔值......所以我不确定为什么这会破坏。实际的堆栈跟踪全部在供应商代码中,没有引用我的代码。

我从其他帖子中看到错误版本的区域(0.7.3)可能会导致错误,但我已经尝试了应该有效的版本(0.7.2& 0.7.4)。该应用程序的其余部分是由angular-cli构建的。

我还注意到,当我只注释掉路由的canActivate属性时,我的代码工作正常......因此canActivate特有的东西正在破坏。

1 个答案:

答案 0 :(得分:2)

CanActivateAuthGuard添加到模块的提供程序应该可以解决此错误。