我在学习角度时遇到了问题。当我从一个Observable获取数据时,在NgOnInit方法中,没关系,该方法带来了正确的值。可悲的部分是当我尝试在外面的任何地方进行访问时,它给了我一个未定义的数组。**
@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());
}
当我打电话时,在Subscribe()
之外的任何地方console.log(this._operacoes);
我得到了未定义的