Alex L
Alex L

Reputation: 119

How do to code an angular observable to return flat values when mapped

I'm writing code where a customer is not allowed on a page if a value is set to true I now have working code but my gut tells me that it is not the most efficient use.

The code is:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
    let bar= false;
    this.foo$.subscribe((x) => {
        bar = x;
    });

    return !bar;
}

But I want it to look like this:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
    return this.foo$.subscribe((x) => {
        return x;
    });
}

The problem is that it keeps returning a Observable if I use it like this and the canActivate function of the guard is not working whit this Observable.

Upvotes: 0

Views: 86

Answers (1)

basst314
basst314

Reputation: 184

If this.foo$ is an Observable<boolean> then you could simply negate the boolean value in a map() function (see documentation) and return the resulting Observable like this:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
    return this.foo$.map(x => !x);
}

Your first code snippet will not work reliably because of the asynchronous foo$ subscription. The function will probably always return true, before the foo$.subscribe() method was called

Upvotes: 2

Related Questions