web-dev-qa-db-ja.com

エラー:キャッチされていません(約束されています):TypeError:ガードは機能ではありません

ログインせずにルートにアクセスできないように、Angular 4でAuthguardを記述しています。ただし、このエラーが発生します。以下は、AuthgaurdとRouting inAppモジュールのコードです。問題の解決にご協力ください。

// Authgaurdコード

import { ActivatedRouteSnapshot, CanActivate, Route, Router, 
RouterStateSnapshot } from '@angular/router';
import { Store } from '';
import { Observable } from 'rxjs/Observable';
import { map, take } from 'rxjs/operators';
import { Observer } from 'rxjs';
import { Globals } from '../../app.global';
import { CRMStorageService } from '../services/storage.service';
import 'rxjs/add/operator/take';

@Injectable()
export class AuthGuard implements CanActivate {

constructor(private router: Router,private storageService: StorageService) { 
 }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): 
Observable<boolean> {
return this.storageService.getItem(Globals._CURRENT_USER_KEY).take(1).map 
(token => {
    if (token) {
        return true;
    } else {
        this.router.navigate(['/login']);
    }
  });
}
}

// Appモジュールのルート

const appRoutes: Routes = [
{ path:'',redirectTo:'/login', pathMatch: 'full' },
{ path:'login', component: LoginComponent },
{ path:'reset/:token', component: ResetpasswordComponent },
{
path: '',
canActivateChild: [AuthGuard],
children: [
{ path:'dashboard', component: DashboardComponent },
{ path:'customerlist', component: CustomerlistComponent }
]
},
{ path: '**', component: ErrorComponent }
];

@NgModule({
imports: [
        RouterModule.forRoot(appRoutes,
        {
         enableTracing: false // <-- debugging purposes only
        })],
 declarations: [
  AppComponent,
 .
 .
],
providers: [AuthGuard],
exports: [],
bootstrap: [AppComponent]})

export class AppModule { }
6
user8300647

ルーティングハンドラーでcanActivateChildcanActivateに置き換えるだけで機能します

const appRoutes: Routes = [
    { path: '', redirectTo: '/login', pathMatch: 'full' },
    { path: 'login', component: LoginComponent },
    { path: 'reset/:token', component: ResetpasswordComponent },
    {
        path: '',
        canActivate: [AuthGuard],
        children: [
            { path: 'dashboard', component: DashboardComponent },
            { path: 'customerlist', component: CustomerlistComponent }
        ]
    },
    { path: '**', component: ErrorComponent }
];

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes,
            {
                enableTracing: false // <-- debugging purposes only
            })],
    declarations: [
        AppComponent,
    .
    .
    ],
    providers: [AuthGuard],
    exports: [],
    bootstrap: [AppComponent]
})

export class AppModule { }
8
Vasim Hayat

CanActivateChildで使用するには、AuthGuardにCanActivateCanAcitvateChildの両方のインターフェースを実装する必要があります。

export class AuthGuard implements CanActivate, CanActivateChild {
  ...
  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):  boolean {
      return this.canActivate(route, state);
 }
}
14
omyfish