I have a problem using an observable. While I'm inside the NgOinit method, when fetching the data, I get the array correctly and hedge in the class variable. However, when I try to access the data outside the subscribe, I get undefined in response. Does anyone know why this occurs?
@Component({
moduleId: module.id,
selector: 'operacao',
templateUrl: './operacao.component.html',
providers: [Operacao],
styleUrls: ['./operacao.component.css']
})
export class OperacaoComponent implements OnInit {
private _operacao: Operacao;
private _operacoes: any[];
public rows: Array<any> = [];
private myserviceService: MyserviceService;
...
constructor(myservice: MyserviceService) {
this.length = 10;
this.myserviceService = myservice;
}
...
ngOnInit() {
this.myserviceService.getOperacoes()
.subscribe((operacao) => {
this._operacoes = operacao;
//here i get the "right" value
console.log(this._operacoes);
//Array(2) [Object, Object]
//0:Object {id: 0, acao_id: 0, user_id: "1", …}
//1:Object {id: 1, acao_id: 1, user_id: "1", …}
myservice.ts
getOperacoes() {
return this.http.get(this.url + 'operacoes').map(res => res.json());
}
When I try to access the data outside the observable, I get undefined.
console.log(this._operacoes);