1

First let me say thank you to all the JHispter developers and also that this project is amazing.

I have a Jhipster 4.14.0 microservices app that uses JWT.

I am trying to replace the menu with one from PrimeNG.

This works fine, but I need to access

principal.isAuthenticated()

and

principal.hasAnyAuthority(['ROLE_ADMIN'])

from ngOnInit or another way to load the menu data. This always returns false. I tried some other lifecycle methods and principal.isAuthenticated() eventually returns true after quite a few calls.

ngAfterContentChecked() {
    console.log('ngAfterContentChecked');
    console.log(this.principal.isAuthenticated());
}

This works fine when I use isAuthenticated from html

<div>{{isAuthenticated()}}</div>

,but I want to control the menu by creating a menu model in the component, but I cannot figure out how to load it correctly.

if(!this.isAuthenticated()) {
  this.model.push({ label: 'Sign in', icon: 'fa fa-fw fa-sign-in', command: (onclick)=> {this.login()} });
} else {
  this.model.push({ label: 'Sign out', icon: 'fa fa-fw fa-sign-in', command: (onclick)=> {this.logout()} });
}

I also tried adding the following to ngOnInit in NavbarComponent.ts

    this.principal.identity().then((account) => {
        this.currentAccount = account;
    });

,but I get this error in the chrome console.

core.js?593e:1440 ERROR TypeError: _this.connectedPromise is not a function
    at eval (tracker.service.ts?aa77:50)
    at eval (webstomp.js?afe9:292)
    at Array.forEach (<anonymous>)
    at SockJS.ws.onmessage (webstomp.js?afe9:284)
    at SockJS.EventTarget.dispatchEvent (eventtarget.js?d62b:51)
    at eval (main.js?8e93:274)
    at Array.forEach (<anonymous>)
    at SockJS._transportMessage (main.js?8e93:272)
    at WebSocketTransport.EventEmitter.emit (emitter.js?a8c1:50)
    at WebSocketTransport.ws.onmessage [as __zone_symbol__ON_PROPERTYmessage] (websocket.js?a354:35)
defaultErrorLogger @ core.js?593e:1440
ErrorHandler.handleError @ core.js?593e:1501
next @ core.js?593e:5481
schedulerFn @ core.js?593e:4319
SafeSubscriber.__tryOrUnsub @ Subscriber.js?3959:240
SafeSubscriber.next @ Subscriber.js?3959:187
Subscriber._next @ Subscriber.js?3959:128
Subscriber.next @ Subscriber.js?3959:92
Subject.next @ Subject.js?8398:56
EventEmitter.emit @ core.js?593e:4299
(anonymous) @ core.js?593e:4755
ZoneDelegate.invoke @ zone.js?6524:388
Zone.run @ zone.js?6524:138
NgZone.runOutsideAngular @ core.js?593e:4681
onHandleError @ core.js?593e:4755
ZoneDelegate.handleError @ zone.js?6524:392
Zone.runTask @ zone.js?6524:191
ZoneTask.invokeTask @ zone.js?6524:495
invokeTask @ zone.js?6524:1536
globalZoneAwareCallback @ zone.js?6524:1562

Any advice would be greatly appreciated on how to get the menu to load correctly based on authentication or roles when the app first loads. The menu works fine, otherwise.

5
  • How do you make sure that principal gets valued before going to your component? This could work only if the menu is not included in home page, so it highly depends on how you architectured your app. If you can't change this then you could try to hide/show menu items. Feb 23, 2018 at 21:05
  • The plan was to include the menu on the home page and determine what to display based on the principal. I am trying to skin my Jhipster app with the PrimeNG Apollo Premium Application Template. The menu is on the home page, and I am not sure the best way to deal with this problem. primefaces.org/primeng-apollo I tried APP_INITIALIZER injection token, but as I suspected this is run before the principal gets valued.
    – Jason Long
    Feb 24, 2018 at 4:29
  • I also tried using a named router outlet, but I have not been successful in loading a different component for "/" and other routes. <router-outlet name="app-menu"></router-outlet>
    – Jason Long
    Feb 24, 2018 at 4:30
  • The following worked. ngOnInit() { setTimeout(() => { this.loadMenu(); }, 0); }
    – Jason Long
    Feb 24, 2018 at 5:06
  • Great, have you tried a prod build too? Because using AOT could break things. Feb 24, 2018 at 9:27

2 Answers 2

0

I was also wondering if this would work in a production build. The setTimeout method did not wait in the production build.

ngOnInit() { 
  setTimeout(() => { 
    this.loadMenu(); 
  }, 0); 
}

The only thing I have been able to get to work so far is using setInterval in ngOninit. I keep polling to see if a user is authenticated and then load the menu and clear the interval.

    ngOnInit() {

      /**
       * This will load the menu, but only show items that do not require login
       * because the principal is not valued yet.
       */
      this.loadMenu();

      /**
       * This interval will run until the user is authenticated and then will reload the menu and clear the interval.
       */
      this.intervalId = setInterval(() => {
          if(this.isAuthenticated()) {
              this.loadMenu();
              clearInterval(this.intervalId);
          }
      }, 100);
    }

This seems like a hack to me and I feel there must be a better way. Maybe create a menu service that observes the principal? If anyone has any I ideas please let me know.

0

I did this in navbar.component.ts:

ngOnInit() {
    this.registerAuthenticationSuccess();
  }


  registerAuthenticationSuccess() {
    this.eventManager.subscribe('authenticationSuccess', (message) => {
      this.getAccount();
    });
  }


  getAccount() {
    this.principal.identity().then((account) => {
      this.account = account;
    });
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.