Search code examples
angularionic-frameworkserviceasync-await

How to get data from a service in ngOnInit Angular


I've a problem trying to get data in ngOnInit from a http service. I need to set my data in a var when the component is fired, so I can use it in another functions.

I've achieved this by doing async ngOnInit, and receiving the response from a Promise function, but I dont think its a good practice ? How can I improve it?

Here is my code:

COMPONENT.TS



     async ngOnInit() {
        this.username = localStorage.getItem('username');
        this.segment.value = 'FUNCIONAL';
        this.categoria = this.segment.value;
        this.listadoClases = await this.claseServicio.obtenerListadoClases(this.categoria); // **Need to set this variable at onInit**


SERVICE.TS


    getClases(actividad) {
        return this.http.get(`https://anders-test.herokuapp.com/clases/obtenerPorCategoria/${actividad}`);
      }


      obtenerListadoClases(categoria) {
        return new Promise(resolve => {
          this.getClases(categoria).subscribe(data => {
            if (data) {
              resolve(data)
            }
          })
        })
      }

Im doing this because Im trying to learn/understand async/await. I want to level up my code a little bit.. But Im not getting the idea after reading a lot..

Thanks in advance guys!


Solution

  • Nyco, why on earth do you make the things so complex?

    The service

      getClases(actividad) {
            return this.http.get(`https://anders-test.herokuapp.com/clases/obtenerPorCategoria/${actividad}`);
          }
    

    The component

    //inject the service in constructor
    constructor(private service:Service){}
    
    ngOnInit() {
        this.username = localStorage.getItem('username');
        this.segment.value = 'FUNCIONAL';
        this.categoria = this.segment.value;
        this.service.getClases(this.categoria).subscribe(res=>{
            this.categorias=res
        })
    }
    

    You should avoid subscribe in services except for some special function. Think that Angular is make over Observables. If you need convert an Observable in Promise, should be a good reason for this