2016-11-09 59 views
0

我是Angular 2的新手,我有一點問題: 我從服務asynrochnus加載數據。 數據到達我的組件,我可以處理它。 這裏我將數據保存在局部變量中。Angular 2處理數據異步

Here's從組件的代碼:

export class ConfigurationComponent implements OnInit { 

    private tab: string = 'general'; 
    private config = []; 

    constructor(private router: Router, private variables: Variables, private apiService: ApiService) { 
     if (!this.variables.getIsLoggedIn()) { 
      this.router.navigate(['login']); 
     } 
    } 

    ngOnInit() { 
     this.getConfigService(); 
    } 

    getConfigService() { 
     this.apiService.getConfigService(). 
     subscribe(
      data => { 
       this.config = data.settings.section; 
      }, 
      //error => this.error = <any>error, 
      error => this.variables.setFailure(error) 
      //() => console.log('done:' + this.status) 
     ); 
    } 

而且here's在HTML的代碼:

<th>{{config[5].entry.name}}</th> 
<th>{{config[5].entry.text}}</th> 

的問題是,在時間視圖時的負荷,局部變量'config'只是'[]'。所以'config [5]'失敗。 但是,如果我沒有在組件中定義本地變量,它也會失敗。

有人可以幫我嗎?

謝謝!

回答

1

您應該將data.settings.section中的每個元素都插入到config中,並檢查它是否存在於視圖中;

//in component 
data.settings.section.forEach(i => this.config.push(i)); 

//in html 
<div *ngIf="config[5]"> 
    {{config[5].entry.name}} 
</div> 

我希望它有幫助!

+0

是的,它有幫助;) – Junias