Seven
Seven

Reputation: 390

Function calls are not supported in decorators in routing module

I want to enter different component in one URL by configuration:

routing.module.ts

const routes = [ 
  // ...
  {
    path: 'members',
    component: applicationInjector.get(ConfigurationService).isAuth
      ? MembersAuthComponent
      : MembersNoAhthComponent
  },
];

main.ts

export let applicationInjector: Injector = null;

platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .then(componentRef => {
    applicationInjector = componentRef.injector;
  })
  .catch(err => console.error(err));

It works fine when I run ng serve, but has the error during ng build --prod: Error during template compile of 'routingModule' Function calls are not supported in decorators but 'applicationInjector' was called.

Upvotes: 1

Views: 146

Answers (2)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24404

you can create an empty component just to disaply the nedded component base of the login state

Member Wrapper Component

export class MemberWrapperComponent {

  constructor(private configServ:ConfigurationService) { }

  get isAuth(){
    return this.configServ.isAuth;
  }

}

template

<ng-container *ngIf="isAuth;else notAuthMember">
  <app-member></app-member>
</ng-container>

<ng-template #notAuthMember>
 <app-unauthorized-member></app-unauthorized-member>
</ng-template>

demo 🚀

Upvotes: 0

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24404

this is the best case to use angular router guard

Memeber Login Guard

@Injectable({
  providedIn: 'root'
})
export class MemeberGuard implements CanActivate {
  constructor(private ConfigService: ConfigurationService, private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.configServ.isAuth) {
      return true;
    } else {
      this.router.navigateByUrl('/notauthorized-members');
      return false;
    }
  }
}

routes

const routes = [ 
  {
    path: 'members', 
    component: MembersAuthComponent,
    canActivate: [MemeberGuard ]
  }, 
{
    path: 'notauthorized-members', 
    component: MembersNoAhthComponent
  }, 
];

read this helpful article Better Redirects in Angular Route Guards

Upvotes: 2

Related Questions