Search code examples
angulartypescriptamazon-cognitoaws-amplify

Array returning empty on ngOnInit


I have set up a project that uses cognito to handle user registration/login This is all working but I am now wanting to make certain pages of the application only visible to admins

My User object has an attribute for permissions and if that is "All" the user is considered an admin

This is what is being returned for my uuser call

{Books: ["all"], LibraryAdmin: true, permissions: ["all"],…}
email: "[email protected]"
key: "{{user key}}"
permissions: ["all"]
primaryLibrary: "City"
LibraryAdmin: true

I am currently using a http get request to get the currently logged in users details

USER COMPONENT

getCurrentUser() {
    this.apiservice
      .getCurrentUser()
      .subscribe((result: any) => {
        this.currentUser = result;
        if(this.currentUser.permissions.includes('all')){
          console.log('Admin')
          this.admin = true;
        }
        else{
          console.log('not admin')
          this.admin = false;
        }
      });

      
  }

Then within the App components ngOnInit I am running getCurrentUser()

App Component

public async ngOnInit(): Promise<void> {
    this.cognitoService.isAuthenticated()
    .then((success: boolean) => {
      this.isAuthenticated = success;

      this.user.getCurrentUser()
      this.admin = this.user.admin;
      console.log(this.admin);
      
    });

This is isAuthenticated in the cognitoService, this is currently returning and working as intended (nav items only show if isAuthenticated is true, see below)

 public isAuthenticated(): Promise<boolean> {
    if (this.authenticationSubject.value) {
      return Promise.resolve(true);
    } else {
      return this.getUser()
        .then((user: any) => {
          if (user) {
            return true;
          } else {
            return false;
          }
        })
        .catch(() => {
          return false;
        });
    }
  }

Then Within my navigation bar I am using an ngIf to only show a link if the user is an admin

 <li  class="nav-item">
          <a class="nav-link" routerLink="/user" routerLinkActive="active" *ngIf="isAuthenticated && admin">User Management</a>
        </li>

The main issue I am having is that when getCurrentUser is called initially during ngOnInit it returns an empty value, because of this the "Admin" value is false.

Any help would be appreciated


Solution

  • First of all, I see you retrieve UserComponent probably by ViewChild. It's not good pattern especially for data passing. The whole logic under subscribe is executed asynchronously and you cannot know when it's finished. Anyway, you can try and it will solve you issue, but still won't be perfect.

    public async ngOnInit(): Promise<void> {
      this.cognitoService.isAuthenticated()
        .then((success: boolean) => {
            this.isAuthenticated = success;
      
            this.apiService.getCurrentUser().subscribe((currentUser: any) => {
                this.admin = currentUser.permissions.includes('all');
                console.log(this.admin)
            }
          
          });
        });