等待继续-Angular 6

时间:2018-10-02 16:15:31

标签: angular typescript

我需要任何解决方案来解决此问题。我需要读取一个将从http请求接收数据的属性。因此,仅在事务完成时才需要测试此属性。

  checkAuthorization(path: string): boolean{
    const usuarioLogado: UsrStoraged = this.storage.getUsuarioLogado();
    let usuario: Usuario
    this.usuarioService.findByLogin(usuarioLogado.login).subscribe(
        data => {
            usuario = data
        }

    )

    if (usuario.perfil.springSecurity == 'ROLE_ADMIN'){
        return true;
    } else {
        const message: Message = {message: 'Usuário sem permissão', type: TipoMensagem.ERROR}
        this.message.notify(message)
        return false;

    }
}

2 个答案:

答案 0 :(得分:1)

您必须修改函数以返回可观察的值,然后使用map将数据转换为布尔结果。

checkAuthorization(path: string): Observable<boolean>{
    const usuarioLogado: UsrStoraged = this.storage.getUsuarioLogado();
    return this.usuarioService.findByLogin(usuarioLogado.login).pipe(map(
        data => {
            const usuario = data

            if (usuario.perfil.springSecurity == 'ROLE_ADMIN'){
                return true;
            } else {
                const message: Message = {message: 'Usuário sem permissão', type: TipoMensagem.ERROR}
                this.message.notify(message)
                return false;
            }
        }
    ))
}

如果还没有导入,还需要添加导入:

import {Observable} from "rxjs"
import {map} from "rxjs/operators"

然后,您必须修改任何调用此函数的代码以订阅结果。例如。代替

if (checkAuthorization("foo")) {
    // do stuff
} else {
    // do other stuff
}

您将使用

checkAuthorization("foo").subscribe(isAuthorized => {
    if (isAuthorized) {
        // do stuff
    } else {
        // do other stuff
    }
})

答案 1 :(得分:-1)

data => {将在您收到时被调用,因此您可以像这样将代码移入内部:

checkAuthorization(path: string): boolean{
    const usuarioLogado: UsrStoraged = this.storage.getUsuarioLogado();
    let usuario: Usuario
    this.usuarioService.findByLogin(usuarioLogado.login).subscribe(
        data => {
            usuario = data
            if (usuario.perfil.springSecurity == 'ROLE_ADMIN'){
                return true;
            } else {
                const message: Message = {message: 'Usuário sem permissão', type: TipoMensagem.ERROR}
                this.message.notify(message)
                return false;

            }
        } 
    );
}

提示::要处理错误情况,请在下面的error => {}中添加data类似物。