Service variable comes as UNDEFINED in the Angular component 2

0

I can not get a variable from a non-angular service. I have the companies-index.component.ts and the companies-crud.service.ts. I would like to get a service variable in the component but it always comes as UNDEFINED, but if I run within the service some function it returns normal.

I am doing a crud in separate file to get better organized. Follow the codes

companies-index.component.ts

import { Component, OnInit } from '@angular/core';

import { EmpresasCrudService } from './services/empresas-crud.service';

import {PagerService} from './services/pagination';

@Component({
  selector: 'empresas-index',
  templateUrl: 'app/cadastros/empresas/empresas-index.component.html',
  styleUrls: ['app/cadastros/empresas/empresas-index.component.css']
})
export class EmpresasIndexComponent implements OnInit{

    constructor(private dataService: EmpresasCrudService, private pagerService: PagerService) {

  }
     // array of all items to be paged
    public allItems: any[];

    // pager object
    pager: any = {};

    // paged items
    pagedItems: any[];

    _page = 1;
    _mostrar = 1;
    _qtd;
    _loading = false;
    Items;

    getEmps(page: number, mostrar:number){


        this.dataService.getEmpresas(page, mostrar);
        console.log(this.dataService.allItems);

    }



    ngOnInit(){
      this.getEmps(this._page,this._mostrar);

    }




}

Company-crud.service.ts

import { Injectable, Input, Output } from '@angular/core';
import { HttpService } from '../../../shared/services/http.service';
import {Observable} from 'rxjs/Rx';

// Import RxJs required methods
import 'rxjs/add/operator/map';

import {Empresa} from '../models/empresas';
import {ListResult} from '../models/pagination';

//import 'rxjs/add/operator/catch';

@Injectable()
export class EmpresasCrudService {


    constructor(private _http: HttpService) {
    }

    //Url
    _endpoint_url: string = 'http://www.sysferaser.com/data/';
    //Itens a pegar da API
    allItems: any[];
    //Quantidade de itens totais da API
    _qtd;

    //faz a requisição
    getHttpEmpresas(page:number, mostrar:number): Observable<ListResult<Empresa>> {
        return this._http.httpGet(this._endpoint_url + mostrar + "?page=" + page)
            .map(response => response.json());
    }

    //Atribui os dados nas variáveis allItems e _qtd
    getEmpresas(page:number, mostrar:number){
        this.getHttpEmpresas(page, mostrar)
            .subscribe(
                people => {
                    this.allItems = people.data,
                    this._qtd = people.total
                },
                error => console.error('Error: ' + error),
                () => console.log('Completed!')

            );
    }


}
    
asked by anonymous 24.11.2016 / 12:41

1 answer

1

I suggest a change in your coding. You are making the entire ajax request within your service. It may be, but I prefer that part of the process be performed inside the component. This way you can make Forks, manipulate the request better among other situations.

I suggest you change your encoding to the following:

companies-index.component.ts

import { Component, OnInit } from '@angular/core';
import { EmpresasCrudService } from './services/empresas-crud.service';
import {PagerService} from './services/pagination';

@Component({
  selector: 'empresas-index',
  templateUrl: 'app/cadastros/empresas/empresas-index.component.html',
  styleUrls: ['app/cadastros/empresas/empresas-index.component.css']
})
export class EmpresasIndexComponent implements OnInit{

    constructor(private dataService: EmpresasCrudService, private pagerService: PagerService) {}

    // array of all items to be paged
    public allItems: any[];

    // pager object
    pager: any = {};

    // paged items
    pagedItems: any[];

    _page = 1;
    _mostrar = 1;
    _qtd;
    _loading = false;
    Items;

    getEmps(page: number, mostrar:number){
        this.dataService.getHttpEmpresas(page, mostrar).subscribe(result => {
              this.allItems = people.data,
              this._qtd = people.total          
        },
            error => console.error('Error: ' + error),
            () => console.log('Completed!'));
    }

    ngOnInit(){
      this.getEmps(this._page,this._mostrar);
    }

}

Company-crud.service.ts

//import 'rxjs/add/operator/catch';

@Injectable()
export class EmpresasCrudService {


    constructor(private _http: HttpService) {
    }

    //Url
    _endpoint_url: string = 'http://www.sysferaser.com/data/';
    //Itens a pegar da API
    allItems: any[];
    //Quantidade de itens totais da API
    _qtd;

    //faz a requisição
    public getHttpEmpresas(page:number, mostrar:number){
        return this._http.httpGet(this._endpoint_url + mostrar + "?page=" + page)
            .map(response => response.json());
    }

}

This will work well for you. You will have access to the ajax request returns and all your variables will be populated. There in front when you need to make multiple requests on which one depends on the other, you can use the fork and everything becomes easier.

I did not really understand why you created the "shared / services / http.service" service. But anyway .. that should work there.

This approach will work for you, but if you really need the structure you mentioned earlier, put it there that we look for the solution together. hug!

    
24.11.2016 / 14:27