Feedback a observable Boolean method

Asked

Viewed 194 times

0

I have a method that should be returned a boleano according to the service response.

I am unable to return true or false outside the observable. Any hints?

checkPermission(route): boolean {
    let permissao = this.loginService
        .checkPermission(route)
        .subscribe(permission => {
            if (!permission[0]) {
                return false
            } else {
                return = true;
            }
        });

    return permissao;
}
  • 2

    You’re never gonna make it, permission is a variable whose value is returned from an asynchronous function when it Return permission value not yet returned from API.

2 answers

1

The checkPermission will only invoke the content within your subscribe when it completes the task that has been delegated to it, for example a request. See that it is an asynchronous process, then the first method checkPermission(route): boolean ... cannot return a boolean.

Since you didn’t post the context I’ll leave an example:

// Quando o checkPermission for finalizado ele irá 
// dar um valor á variável permissaoRota
permissaoRota = false;
checkPermission(route): boolean {
    this.loginService
        .checkPermission(route)
        .subscribe(permission => {
            permissaoRota = !permission[0];
        });
}

 // No seu template:
<div *ngIf="permissaoRota">rota xyz</div<

Another example converting to Promise:

checkPermission(route): Promise<boolean> {
    return this.loginService
        // suponho que a função abaixo retorne um Observable<boolean>
        .checkPermission(route)
        .toPromise();
}

// Exemplo de como usar o método
async teste() {
    try {
        const permissaoRota = await checkPermission('minha rota');
    } catch(err) { /* ... */ }
}

0

You can use await to wait for service response or your checkPermission() method to return an Observable< Boolean >;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.