Angular / Typescript-布尔变量不在.subscribe上更新

时间:2020-11-04 17:01:10

标签: angular typescript .net-core angular-httpclient

我在服务器端具有此功能,暂时被迫返回true:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
        [HttpGet("cPasaAJefeVentas")]
        public async Task<IActionResult> CPasaAJefeVentas(string idPais, string idCompania, string idSalesorg, string idDivision, string idUser, decimal porcentaje)
        {
          
            return Ok(true);

        }

这是您在服务内部的客户端上调用它的方式:

cPasaAJefeVentas(idPais: string , idCompania:string, idSalesOrg:string, idDivision:string, idUser:string, porcentaje:number) {
        return this.http.get(this.altapedidosserveruri + 'cPasaAJefeVentas?=' + idPais + '&idCompania=' + idCompania + '&idSalesOrg=' + idSalesOrg + '&idDivision=' + idDivision + '&idUser=' + idUser + '&porcentaje=' + porcentaje);
    }

这是我现在遇到问题的地方:

 cPasaJefeVentas(): boolean {
    let descuentoDiscrecional: number = 5;
    let res: boolean = null;
    this.altaPedidosService
      .cPasaAJefeVentas(this.pedidoObjeto.idPais, this.pedidoObjeto.idCompania,
        this.pedidoObjeto.idSalesOrg, this.pedidoObjeto.idDivision, this.loggedService.logged.UserName, descuentoDiscrecional)
      .subscribe((result: boolean) => (
        console.log(result),
        res = result
      ))
    return res;
  }

console.log(result)打印TRUE,这是正确的,但是我想将返回的值赋给“ res”变量,并且它不起作用,因为退出.susbscribe时它仍然为null。 / p>

我想知道我在这里做错了什么吗?为什么“ res”变量的值不像应该更新的那样?

1 个答案:

答案 0 :(得分:0)

您的服务正在返回可观察的响应。 可观察对象是异步的,您不能保证何时收到响应。因此,修改您的方法以返回 Observable 响应。您的代码将像这样被修改

 cPasaJefeVentas(): Observable<boolean> {
    let descuentoDiscrecional: number = 5;
    let res: boolean = null;
    let response$ = this.altaPedidosService
      .cPasaAJefeVentas(this.pedidoObjeto.idPais, this.pedidoObjeto.idCompania,
        this.pedidoObjeto.idSalesOrg, this.pedidoObjeto.idDivision, this.loggedService.logged.UserName, descuentoDiscrecional)
      .subscribe((result: boolean) => (
        console.log(result),
        res = result
      ));
      
      return response$;
  }

在模板中,您可以应用 async 管道以显示可观察的值,例如

<p>{{cPasaJefeVentas() | async}}</p>