Get or return a variable to the angular

Asked

Viewed 217 times

0

I have a method where I do a certain validation and depending on the scenario, I need to return only an alert and continue with the request or a possible Badrequest also returning a message.

I thought I’d try to access a variable inside mine if using the angular. Or send some feedback to my controller of angular.

I need to get the variable that’s in if :

(if (damMesAnterior != null))

In case it meets this validation.

private async Task VerificarDam(NotaViewModel nota, Prestador prestador)
    {
        var timezone = TimeZoneInfo.FindSystemTimeZoneById("E. South America Standard Time");
        var dataAtual = TimeZoneInfo.ConvertTime(DateTime.Now, timezone);

        if (dataAtual.Day >= 16)
        {
            var damDoisMesesAnterior = await (DbContext.ValidarPagamentoDAM(nota.Competencia.Value, prestador.Id));

            var damMesAnterior = await (DbContext.VerificarDamCompAnterior(nota.Competencia.Value, prestador.Id));

            if (damMesAnterior != null)
            {
                //Nesse bloco que preciso enviar essa variavel para o front

                var msg = "Mensagem de teste atraso.....";
            }

            if (damDoisMesesAnterior != null)
            {
                if (prestador.DataLiberacao != null)
                {
                    if (prestador.DataLiberacao < dataAtual)
                    {
                        BadRequest(
                            "Existem pendências. Entre em contato com ...");
                    }
                }
            }
        }
    }

Angular controller where I get request data:

    $scope.emitir = function () {
    notaService.emitir($scope.nota).then(function (results) {
        var nota = results.data;

        logService.success('teste mensagem de sucesso.');

        var email = nota.user.email;
        notaService.emitirXML(nota.value2.prestador.value1, nota.value2, nota.value3).then(function (resultsXML) {
            if (email) {
                var url = 'nota.html#/nota/' + nota.prestador.value1 + '/' + nota.value2 + '/' + notaGerada.verificador;
                var baseLen = $location.absUrl().length - $location.url().length;
                url = $location.absUrl().substring(0, baseLen - 1) + url;
                notaService.enviarNota(url, email).then(function (results) {
                    notaService.apagarXML(nota.prestador.value1, nota.value2, nota.value3).then(function (result) {
                    }, function (error)
                        {
                        logService.log(error);
                        console.log(error);
                        });
                },
                    function (error)
                    {
                        logService.log(error);
                        console.log(error);
                    });
            }
        }, function (error) {
            logService.log(error);
        });
        $scope.newNota();
        $scope.initNota();
        $window.open('nota.html#/nota/' + nota.prestador.value1 + '/' + nota.value2 + '/' + nota.value3);


    }, function (error) {
        logService.log(error);
        $scope.nota.valid = true;
    });
};

Method is where I make certain validations and return to the public method (which is my action), which is accessed by angular:

   public async Task<IHttpActionResult> Emitir(NotaViewModel nota)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        var prestador = await DbContext.GetContribuinteByUserIdAsync(this.User.Identity.GetUserId());

        await VerificarDam(nota, prestador);

        var valueNota = new Nota
        {
            Valor1 = nota.Valor1,
            Valor2 = nota.Valor2,
            Valor3 = nota.Valor3,
            Valor = nota.CofiValorns,
        };
        DbContext.Servicos.Add(valueNota);

        await DbContext.SaveChangesAsync();

        nota = await GetNotaAsync(valueNota);

        return Ok(nota);
    }
  • That method Check is a action of your controller?

  • Can you add this public method to the question?

  • It’s a basic registration method. If you really need it, I can share the code.

  • is that the return to the angular is in this access method, I can make an example without seeing it, but it is better to see

  • I’ll share then. Just a second.

  • 1

    in his IHttpActionResult you already return an object of type "note"(return Ok(nota);), if to return something from VerificarDam will change this return, this is what you want?

  • Yes. But this message I only need to send according to the rules applied in the method. It can happen the situation where I can also perform an Insert and in it n return any of these validation messages.

Show 2 more comments

1 answer

1


You can return one json with the information you want

your code can be like this:

A class was created to treat return of the method, in it was added a field for status and another for message

the verification method returns an object of type retorno and, finally, in the controller status is checked and this object is returned.

at the angle you can capture that return and treat the message

public class Retorno
{
     public int StatuCode { get; set; }
     public string MensagemRetorno { get; set; }
}

public async Task<Retorno> VerificarDam(NotaViewModel nota, Prestador prestador)
{
    var timezone = TimeZoneInfo.FindSystemTimeZoneById("E. South America Standard Time");
    var dataAtual = TimeZoneInfo.ConvertTime(DateTime.Now, timezone);

    if (dataAtual.Day >= 16)
    {
        var damDoisMesesAnterior = await (DbContext.ValidarPagamentoDAM(nota.Competencia.Value, prestador.Id));

        var damMesAnterior = await (DbContext.VerificarDamCompAnterior(nota.Competencia.Value, prestador.Id));

        if (damMesAnterior != null)
        {
            return new Retorno{
                StatuCode = 200,
                MensagemRetorno = "Mensagem de teste atraso....."
            };
        }

        if (damDoisMesesAnterior != null)
        {
            if (prestador.DataLiberacao != null)
            {
                if (prestador.DataLiberacao < dataAtual)
                {
                    return new Retorno{
                        StatuCode = 400,
                        MensagemRetorno = "Existem pendências. Entre em contato com ..."
                    };
                }
            }
        }
    }

    return new Retorno{
        StatuCode = 200,
        MensagemRetorno = "data atual menor que 16"
    };
}


public async Task<IHttpActionResult> Emitir(NotaViewModel nota)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    var prestador = await DbContext.GetContribuinteByUserIdAsync(this.User.Identity.GetUserId());

    Retorno retorno = await VerificarDam(nota, prestador);

    var valueNota = new Nota
    {
        Valor1 = nota.Valor1,
        Valor2 = nota.Valor2,
        Valor3 = nota.Valor3,
        Valor = nota.CofiValorns,
    };
    DbContext.Servicos.Add(valueNota);

    await DbContext.SaveChangesAsync();

    nota = await GetNotaAsync(valueNota);

    if (retorno.StatuCode == 200)
        return Ok(retorno);
    else
        return ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, retorno));     
}
  • No Return missing in Check method?

  • I added the return where the var msg = "Mensagem de teste atraso....."; and the BadRequest("Existem pendências. Entre em contato com ..."); there’s somewhere else you want to return something?

  • 1

    I say at the end of this if block (dateAtual.Day >= 16), should not return the Return object?

  • 1

    truth, I didn’t pay attention to all If's

Browser other questions tagged

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