Learner
Learner

Reputation: 603

Execute Observable by condition in Angular 7

I would like to execute API call only when condition is true in *ngIf="auth.isLoggedIn(); else anonymousUser": However, the API call to the server is made even auth.isLoggedIn() returns false.

navbar.html:

<ng-container *ngIf="auth.isLoggedIn(); else anonymousUser">                  
    <li *ngIf="appUser$ | async as anUser">
        {{ anUser?.name }}
    </li>
</ng-container>

navbar.ts

export class NavbarComponent implements OnInit {
    appUser$: Observable<AppUser>;      

    constructor(private userService: UserService,
                private auth: AuthService) {
    }

    async ngOnInit() {
        this.appUser$ = this.userService.get();     
    }
}

auth.service.ts:

@Injectable({
  providedIn: 'root'
})
export class AuthService {
    public isLoggedIn() {
    const token = localStorage.getItem('authToken');
    if (token !== 'undefined' && !this.jwtHelper.isTokenExpired(token)) {
      return true;
    }
    return false;
  }    
}

user.service.ts:

@Injectable({
  providedIn: 'root'
})
export class AuthService {
    get(): Observable<AppUser> {
        return super.getById(localStorage.getItem('userId'))
            .pipe(map(s => ( {id: s.id, name: s['userName']
                              , isAdmin: s['isAdmin']})));
    }
}

Could you tell me how can I execute API call when only auth.isLoggedIn() returns true?

Upvotes: 0

Views: 83

Answers (1)

wentjun
wentjun

Reputation: 42576

You can consider using the RxJS filter() operator (not to be confused with the JavaScript Array.filter() method). According to the documentation, it will

Emit values that pass the provided condition.

Hence, this will ensure that the observable will only be completed only if the condition (isLoggedIn returns true) is passed.

ngOnInit() {
  this.appUser$ = this.userService.get()
    .pipe(
      filter(auth.isLoggedIn()),
    );     
}

Upvotes: 3

Related Questions