如何禁用canActivate Guard

时间:2019-09-10 16:43:24

标签: angular angular-router-guards

经过数小时的搜索后,在Web应用程序中实现了CanActivate的位置,但没有发现任何问题。因此,我想问一下您是否有一种通常可以禁用它的方法?无法访问我的网址,但未找到其他任何重定向。每次都会将我发送到登录页面。我不熟悉angular,请原谅。如果您需要一些代码示例,请告诉我。我不确定要提供什么。

编辑(我想是)路由文件:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { DataService } from './data.service';
import { PublicuserService } from './Services/publicuser.service';
import { WardmemberService } from './Services/wardmember.service';
/*import {FileUploadModule} from 'primeng/primeng';*/
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
//import { NgBootstrapFormValidationModule } from 'ng-bootstrap-form-validation';
import { AppComponent } from './app.component';
import { MyLoginComponent } from './my-login/my-login.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { TimelineComponent } from './timeline/timeline.component';
import { LandingPageComponent } from './landing-page/landing-page.component';
import { UserInfoComponent } from './user-info/user-info.component';
import { SubTimelineComponent } from './sub-timeline/sub-timeline.component';
import { EventComponent } from './event/event.component';
import { FriendComponent } from './friend/friend.component';
import { MemberLoginComponent } from './member-login/member-login.component';
import { JobDisplayComponent } from './job-display/job-display.component';
import { AddAdsComponent } from './add-ads/add-ads.component';
import { SearchResultComponent } from './search-result/search-result.component';
/*Social login module*/
import { SocialLoginModule, AuthServiceConfig } from "angular4-social-login";
import { FacebookLoginProvider } from "angular4-social-login";
import { NormalHeaderComponent } from './normal-header/normal-header.component';
import { Ng2FileTypeModule } from 'ng2-file-type';
import { Ng2FileSizeModule } from 'ng2-file-size';
import { PublicUserHeaderComponent } from './public-user-header/public-user-header.component';
import { PublicUserTimelineComponent } from './public-user-timeline/public-user-timeline.component';
import { PublicUserSubTimelineComponent } from './public-user-sub-timeline/public-user-sub-timeline.component';
import { AccceptPublicUserDetailsModalComponent } from './acccept-public-user-details-modal/acccept-public-user-details-modal.component';
import { PublicUserFollowingComponent } from './public-user-following/public-user-following.component';
import { WardMemberPublicProfileComponent } from './ward-member-public-profile/ward-member-public-profile.component';
import { WardMemberPublicProfileTimelineComponent } from './ward-member-public-profile-timeline/ward-member-public-profile-timeline.component';
import { WardMemberPublicProfileAboutComponent } from './ward-member-public-profile-about/ward-member-public-profile-about.component';
import { WardMemberPublicProfileFAQComponent } from './ward-member-public-profile-faq/ward-member-public-profile-faq.component';
import { WardMemberPublicProfileEventComponent } from './ward-member-public-profile-event/ward-member-public-profile-event.component';
import { WardMemberPublicProfileJobComponent } from './ward-member-public-profile-job/ward-member-public-profile-job.component';
import { SharePostComponent } from './share-post/share-post.component';
import { MomentModule } from 'angular2-moment';
import { PostfromFollowingmemberComponent } from './postfrom-followingmember/postfrom-followingmember.component';
import { ShareButtonsModule } from 'ngx-sharebuttons';
import { ShareModule } from 'ng2share/share.module';
import { SelectModule } from 'angular2-select';
import { MyMunicipalityComponent } from './my-municipality/my-municipality.component';
import { PostDetailComponent } from './post-detail/post-detail.component';
import { NgAutoCompleteModule } from "ng-auto-complete";
import { GroupComponent } from './group/group.component';
import { AddGroupMembersComponent } from './add-group-members/add-group-members.component';
import { PostDetailInfoComponent } from './post-detail-info/post-detail-info.component';
import { GroupListComponent } from './group-list/group-list.component';
import { GroupListMemberComponent } from './group-list-member/group-list-member.component';
import { UserGroupComponent } from './user-group/user-group.component';
import { GroupMembersComponent } from './group-members/group-members.component';
import { GroupMemberAboutComponent } from './group-member-about/group-member-about.component';
import { UniversalPageComponent } from './universal-page/universal-page.component';
import { Ng2CompleterModule } from "ng2-completer";
import { SliderModule } from 'ngx-slider';
import { MostAddClickReportComponent } from './most-add-click-report/most-add-click-report.component';
import { DataTableModule } from "angular2-datatable";
import { ReportComponent } from './report/report.component';
import { WardmemberPostCategoryReportComponent } from './wardmember-post-category-report/wardmember-post-category-report.component';
import { WardmemberFellowMemberGroupComponent } from './wardmember-fellow-member-group/wardmember-fellow-member-group.component';
import { WardmemberCounzlorListComponent } from './wardmember-counzlor-list/wardmember-counzlor-list.component';
import { PublicuserPostCategoryReportComponent } from './publicuser-post-category-report/publicuser-post-category-report.component';
import { PublicuserFellowMemberGroupComponent } from './publicuser-fellow-member-group/publicuser-fellow-member-group.component';
import { PublicuserCounzlorListComponent } from './publicuser-counzlor-list/publicuser-counzlor-list.component';
import { PublicuserReportComponent } from './publicuser-report/publicuser-report.component';
import { TooltipModule } from "ngx-tooltip";
import * as FusionCharts from 'fusioncharts';
import * as Charts from 'fusioncharts/fusioncharts.charts';
import * as FintTheme from 'fusioncharts/themes/fusioncharts.theme.fint';
import { FusionChartsModule } from 'angular4-fusioncharts';
import { Nl2BrPipeModule } from 'nl2br-pipe';
import { LinkyModule } from 'angular-linky';
import { AngularDateTimePickerModule } from 'angular2-datetimepicker';

import { DatePipe } from '@angular/common';
import { FollowersPostComponent } from './followers-post/followers-post.component';
import { PostDetailDisplayComponent } from './post-detail-display/post-detail-display.component';
import { FollowersPostGroupComponent } from './followers-post-group/followers-post-group.component';
FusionChartsModule.fcRoot(FusionCharts, Charts, FintTheme);
import { ImageCompressService, ResizeOptions, ImageUtilityService } from 'ng2-image-compress';
import { AngularMultiSelectModule } from 'angular2-multiselect-dropdown/angular2-multiselect-dropdown';
import { LoginServiceService } from './Services/login-service.service';
import { DataProviderService } from './Services/data-provider.service';
import { NgProgressModule } from 'ngx-progressbar';
import { DxDataGridModule, DxPieChartModule } from 'devextreme-angular';
import { LikeCategorywiseReportComponent } from './like-categorywise-report/like-categorywise-report.component';
import { InfiniteScrollModule } from 'ngx-infinite-scroll';

/*Social facebook login */
let config = new AuthServiceConfig([
  {
    id: FacebookLoginProvider.PROVIDER_ID,
    provider: new FacebookLoginProvider('487205825449125'),
  }
]);
export function provideConfig() {
  return config;
}

@NgModule({
  declarations: [
    AppComponent,
    MyLoginComponent,
    HeaderComponent,
    FooterComponent,
    TimelineComponent,
    LandingPageComponent,
    UserInfoComponent,
    SubTimelineComponent,
    EventComponent,
    FriendComponent,
    MemberLoginComponent,
    JobDisplayComponent,
    AddAdsComponent,
    SearchResultComponent,
    NormalHeaderComponent,
    PublicUserHeaderComponent,
    PublicUserTimelineComponent,
    PublicUserSubTimelineComponent,
    AccceptPublicUserDetailsModalComponent,
    PublicUserFollowingComponent,
    WardMemberPublicProfileTimelineComponent,
    WardMemberPublicProfileComponent,
    WardMemberPublicProfileAboutComponent,
    WardMemberPublicProfileFAQComponent,
    WardMemberPublicProfileEventComponent,
    WardMemberPublicProfileJobComponent,
    SharePostComponent,
    PostfromFollowingmemberComponent,
    MyMunicipalityComponent,
    PostDetailComponent,
    GroupComponent,
    AddGroupMembersComponent,
    PostDetailInfoComponent,
    GroupListComponent,
    GroupListMemberComponent,
    UserGroupComponent,
    GroupMembersComponent,
    GroupMemberAboutComponent,
    UniversalPageComponent,
    MostAddClickReportComponent,
    ReportComponent,
    WardmemberPostCategoryReportComponent,
    WardmemberFellowMemberGroupComponent,
    WardmemberCounzlorListComponent,
    PublicuserPostCategoryReportComponent,
    PublicuserFellowMemberGroupComponent,
    PublicuserCounzlorListComponent,
    PublicuserReportComponent,
    FollowersPostComponent,
    PostDetailDisplayComponent,
    FollowersPostGroupComponent,
    LikeCategorywiseReportComponent,
  ],
  imports: [
    SocialLoginModule,
    BrowserModule,
    HttpModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    Ng2FileTypeModule,
    Ng2FileSizeModule,
    MomentModule,
    ShareModule,
    Nl2BrPipeModule,
    LinkyModule,
    NgAutoCompleteModule,
    SliderModule,
    DataTableModule,
    TooltipModule,
    Ng2CompleterModule,
    ShareButtonsModule.forRoot(),
    SelectModule,
    AngularDateTimePickerModule,
    FusionChartsModule,
    AngularMultiSelectModule,
    NgProgressModule,
    DxDataGridModule,
    DxPieChartModule,
    InfiniteScrollModule,
    //  NgBootstrapFormValidationModule.forRoot(),
    RouterModule.forRoot([
      {
        path: '',
        component: UniversalPageComponent
      },
      {
        path: 'login',
        component: MemberLoginComponent
      },
      {
        path: 'report',
        component: ReportComponent,
        children: [
          {
            path: '',
            component: WardmemberPostCategoryReportComponent
          },
          {
            path: 'wardmember-fellow-member-group',
            component: WardmemberFellowMemberGroupComponent
          },
          {
            path: 'wardmember-counzlor-list',
            component: WardmemberCounzlorListComponent
          },
          {
            path: 'most-add-click-report',
            component: MostAddClickReportComponent
          },
          {
            path: 'like-categorywise-report',
            component: LikeCategorywiseReportComponent
          },
        ]
      },
      {
        path: 'publicuser-report',
        component: PublicuserReportComponent,
        children: [
          {
            path: '',
            component: PublicuserPostCategoryReportComponent
          },
          {
            path: 'publicuser-fellow-member-group',
            component: PublicuserFellowMemberGroupComponent
          },
          {
            path: 'publicuser-counzlor-list',
            component: PublicuserCounzlorListComponent
          }
        ]
      },
      {
        path: 'user-profile',
        component: TimelineComponent,
        children: [
          {
            path: '',
            component: SubTimelineComponent
          },
          {
            path: 'followers-post',
            component: FollowersPostComponent
          },
          {
            path: 'user-info',
            component: UserInfoComponent
          },
          {
            path: 'event',
            component: EventComponent
          },
          {
            path: 'followers',
            component: FriendComponent
          },
          {
            path: 'job-display',
            component: JobDisplayComponent
          },
          {
            path: 'add-ads',
            component: AddAdsComponent
          }
        ]
      },
      // {
      //   path:'share-post',
      //   component:SharePostComponent
      // },
      {
        path: 'landing-page',
        component: LandingPageComponent
      },
      {
        path: 'my-municipality/:org_name',
        component: MyMunicipalityComponent
      },
      {
        path: 'postfrom-followingmember',
        component: PostfromFollowingmemberComponent
      },
      {
        path: 'post/:ward-name/:post_id',
        component: PostDetailComponent
      },
      {
        path: 'post-detail/:post_id',
        component: PostDetailDisplayComponent
      },
      {
        path: 'login-redirect',
        component: MyLoginComponent
      },
      {
        path: 'public-user-profile',
        component: PublicUserTimelineComponent,
        children: [
          {
            path: '',
            component: PublicUserSubTimelineComponent
          },
          {
            path: 'following',
            component: PublicUserFollowingComponent
          }
        ]
      },
      {
        path: 'search-result/:ward_name',
        component: SearchResultComponent
      },
      {
        path: 'public-user-details',
        component: AccceptPublicUserDetailsModalComponent
      },
      {
        path: 'group/:ward-name/:group-name',
        component: GroupComponent,
      },
      {
        path: 'followersPostGroup/:ward-name/:group-name',
        component: FollowersPostGroupComponent,
      },
      {
        path: 'group-members/:ward-name/:group-name',
        component: GroupMembersComponent,
      },
      {
        path: 'add-members/:group-id',
        component: AddGroupMembersComponent
      },
      {
        path: 'post-detail-info/:post_id',
        component: PostDetailInfoComponent
      },
      {
        path: 'group-list',
        component: GroupListComponent
      },
      {
        path: 'user-group/:ward-name/:group-name',
        component: UserGroupComponent
      },
      {
        path: 'group-member-about/:ward-name/:group-name',
        component: GroupMemberAboutComponent
      },
      {
        path: 'universal-page',
        component: UniversalPageComponent
      },
      {
        path: ':membercode',
        component: WardMemberPublicProfileComponent,
        children: [
          {
            path: '',
            component: WardMemberPublicProfileTimelineComponent
          },
          {
            path: 'public-about',
            component: WardMemberPublicProfileAboutComponent
          },
          {
              path: 'public-services',
              component: WardMemberPublicProfileFAQComponent
          },
          {
            path: 'public-event',
            component: WardMemberPublicProfileEventComponent
          },
          {
            path: 'public-job',
            component: WardMemberPublicProfileJobComponent
          }
        ]
      },
    ])
  ],
  providers: [
    {
      provide: AuthServiceConfig,
      useFactory: provideConfig,

    },
    DataService,
    WardmemberService,
    PublicuserService,
    DatePipe,
    ImageCompressService,
    ResizeOptions,
    LoginServiceService,
    DataProviderService,
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }

4 个答案:

答案 0 :(得分:1)

尝试返回false

canActivate(): boolean {
   return false;
}

以下链接是canActivate的实现 https://medium.com/@ryanchenkie_40935/angular-authentication-using-route-guards-bf7a4ca13ae3

答案 1 :(得分:1)

  

经过数小时的搜索后,在Web应用程序中实现了CanActivate接口的地方一无所获。

没有一个。...

您正在使用处理登录的第三方库。强制用户登录。

https://github.com/abacritt/angularx-social-login

答案 2 :(得分:1)

后卫不过是一项服务(基本上是一个类),您可以在其中实现CanActivate接口,该接口只返回 true false

这是angular.io

中的实际定义
  

一个类可以实现作为确定是否可以激活路由的后卫的接口。如果所有防护措施都返回true,则导航将继续。如果任何防护措施返回假,导航将被取消。如果任何防护程序返回了UrlTree,则当前导航将被取消,并且新的导航操作将从防护程序返回的UrlTree开始。

这是我编写的示例身份验证防护:

@Injectable({
      providedIn: 'root'
    })
    export class AuthGuard implements CanActivate {
      authenticated: boolean = false;

      constructor(private authService: AuthService, private router: Router) {}

      canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
      ): Observable<boolean> | Promise<boolean> | boolean {
        console.log('auth guard called', 'you are trying to visit', state.url);
        this.authService.isAuthenticated.subscribe((authenticated: boolean) => {
// this is where your logic should be written
          this.authenticated = authenticated;
          console.log('auth guard is authenticated', this.authenticated);
        });
        if (this.authenticated) {
          return true;
        } else {
          // TODO save the redirect url to redirect user back to the desired url 
after authentication
          console.log('going to login page');
          this.router.navigate(['/auth/login']);
          return false;
        }
      }
    }

如您所见,如果isAuthenticated值为true,则CanActivate返回true,否则返回false。

如果它是一个大型应用程序,但您找不到保护服务,请转到路由模块文件,查看已链接到该特定模块的保护。

例如,在路由器模块文件中,您会在Routes数组中找到类似的内容:

 {
    path: 'dashboard',
    loadChildren: () => import('./feature/dashboard/dashboard.module').then(m => m.DashboardModule),
    canActivate: [AuthGuard]
  },

此处,Auth Guard控制仪表板模块的视图。同样,在您的应用程序中,将有一个类似的Guard服务。您需要搜索该服务,并检查CanActivate方法中的逻辑。

希望有帮助!

答案 3 :(得分:0)

您可以为此使用 aop-routing 库。它提供了临时移除导航路线上的 canactivate 守卫的能力,然后在导航完成后恢复更改

https://js.plainenglish.io/dynamically-add-and-remove-canactivate-route-guards-in-angular-e7820ab4e061