2016-11-09 52 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