2016-04-25 5 views
0

Я пытаюсь сделать службу api и назначить данные переменной, но переменная не обновляется и получает как неопределенное, когда я пытаюсь выполнить регистрацию после службы API.Угловая 2, переменная не обновляется внутри службы

import {Component,Input,Output,EventEmitter} from 'angular2/core'; 
import {NgClass,NgFor} from 'angular2/common'; 
import {Observable} from 'rxjs/Observable'; 
import {ChangeDetectionStrategy} from 'angular2/core'; 
import {ValuesPipe} from '../pipes/values'; 
import {ApiRequestService, Query} from '../services/apiRequestService'; 




@Component({ 
selector: 'browsePCLatestRelease', // <home></home> 
directives: [NgClass,NgFor], 
changeDetection: ChangeDetectionStrategy.OnPush, 
pipes: [ ValuesPipe ], 
styles: [ require('./browsePCLatestRelease.less') ], 
template: require('./browsePCLatestRelease.html') 
}) 
export class browsePCLatestRelease { 

public arrayOfKeys; 
pcLatestrelease:Array<any> ; 
query: Query; 

constructor(private _apiService: ApiRequestService) { 
} 

ngOnInit() { 

this.query = this._apiService.createQuery('browsePC.getIssue'); 
this.query.params({ 
    volume: '60', 
    issue: '50' 
}); 
this._apiService.execute(this.query) 
    .subscribe(

    data => this.pcLatestrelease=data, 
    error => console.log(error), 
    () => console.log('pcLatestrelease retrived') 

); 

console.log('this.pcLatestrelease'); 
console.log(this.pcLatestrelease); // logged as undefined 

} 


} 

HTML

<div *ngFor = "#thisRelease of pcLatestrelease"> 
     {{thisRelease.title}} 
</div> 

Может кто-то помочь мне, спасибо заранее.

ответ

1

код не выполняется строка за строкой, как указано в функции

export class browsePCLatestRelease { 

    ... 

    ngOnInit() { 

    this.query = this._apiService.createQuery('browsePC.getIssue'); 
    this.query.params({ 
     volume: '60', 
     issue: '50' 
    }); 
    this._apiService.execute(this.query) 
    .subscribe(
    // here you pass a function to subscribe of an observable 
    // the function gets called when the data arrives (from the server) 
     data => this.pcLatestrelease=data, 
     error => console.log(error), 
    () => console.log('pcLatestrelease retrived') 
    ); 

    // this code is executed immediately after the function (callback) 
    // was passed to subscribe, but the function wasn't yet executed 
    console.log('this.pcLatestrelease'); 
    console.log(this.pcLatestrelease); // logged as undefined 
    } 
} 

когда затем данные поступают в конечном счете

data => this.pcLatestrelease=data, 

выполняется и значение, присвоенное this.pcLatestrelease

Если вы хотите, чтобы ваш код был выполнен после получения данных, используйте

export class browsePCLatestRelease { 

    ... 

    ngOnInit() { 

    this.query = this._apiService.createQuery('browsePC.getIssue'); 
    this.query.params({ 
     volume: '60', 
     issue: '50' 
    }); 
    this._apiService.execute(this.query) 
    .subscribe(
    // here you pass a function to subscribe of an observable 
    // the function gets called when the data arrives (from the server) 
     data => { 
     this.pcLatestrelease=data; 
     console.log('this.pcLatestrelease'); 
     console.log(this.pcLatestrelease); // logged as undefined 
     }, 
     error => console.log(error), 
    () => console.log('pcLatestrelease retrived') 
    ); 

    } 
} 

обновление

import {Component,Input,Output,EventEmitter, NgZone} from 'angular2/core'; 

... 

export class browsePCLatestRelease { 

    constructor(private _apiService: ApiRequestService, private _zone.NgZone) { 
    }  

    ... 

    ngOnInit() { 

    this.query = this._apiService.createQuery('browsePC.getIssue'); 
    this.query.params({ 
     volume: '60', 
     issue: '50' 
    }); 
    this._apiService.execute(this.query) 
    .subscribe(
    // here you pass a function to subscribe of an observable 
    // the function gets called when the data arrives (from the server) 
     data => { 
     this.zone.run(() => { 
      this.pcLatestrelease=data; 
      console.log('this.pcLatestrelease'); 
      console.log(this.pcLatestrelease); // logged as undefined 
     }); 
     }, 
     error => console.log(error), 
    () => console.log('pcLatestrelease retrived') 
    ); 

    } 
} 
+0

Спасибо, это работает отлично, но я хочу использовать эту переменную в HTML, –

+0

Это не должно быть проблемой. Угловой может бросить, если вы привяжете себя как 'pcLatestrelease.someProperty'. Вы можете исправить это, используя оператор Elvis, например 'pcLatestrelease? .someProperty', тогда Angular не пытается получить доступ к' .someProperty', пока значение 'pcLatestrelease' не будет иметь значения. –

+0

обновлен с помощью HTML, переменная не обновляется в HTML и отражает новые данные. –

Смежные вопросы