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!')
);
}
}