2016-10-19 90 views
0

我最近开始学习Angular2概念,所以我有一个问题想了解如何使用。然后完成交易后改变ngOnOnit一个布尔“装”值,我的组件从检索数据服务完美。如果有人能够给我一个手将是巨大的。更新变量Angular2

基本上就是我想要做的就是改变值装载到“假”,并隐藏在完成循环后“MD-进步圈”。

这是我的HTML。

<span *ngIf="loading"> 
<md-progress-circle mode="indeterminate"></md-progress-circle> 
</span> 

这是我的组件类。



    import { Component, OnInit } from '@angular/core'; 
    import { Router } from '@angular/router'; 
    import { DemographicsService } from './app.service-http'; 
    import { Demographics } from './demographics'; 

    @Component({ 
     selector: 'app-data', 
     templateUrl: 'app/app.data.html', 
     styleUrls: ['app/app.data.css'] 
    }) 
    export class AppData implements OnInit { 

     demographics: Demographics[] = []; 
     loading: boolean = false; 

     constructor(
     private router: Router, 
     private demographicsService: DemographicsService) { 
     } 

     ngOnInit(): void { 
     this.loading = true; 
     this.demographicsService.getDemographics() 
      .then(demographics => this.demographics = demographics); 
     } 
    } 

添加这样的事情里面。然后

this.loader = false

回答

2

.then的第一个参数是执行一次得出结果的功能。只需添加另一行代码,做你想做什么:

this.demographicsService.getDemographics().then(
    demographics => { 
     this.demographics = demographics; 
     this.loading = false; 
    } 
); 

一件事看出来的:如果承诺被拒绝或如果发生异常,loading=false线将永远不会被执行,应用程序将留在无限的装载状态。

为了解决这个问题,你可能想在.finally块来设定负载来代替。无论如何这个块都得到执行:

this.demographicsService.getDemographics().then(
    demographics => this.demographics = demographics; 
).catch( 
    error => { /* TODO: handle the error*/ } 
).finally( 
    ()=>this.loading=false 
); 
+0

非常感谢,还在学习ES2015概念(箭头函数),非常感谢。 – Dimitri

+0

@Dimitri欢迎您。我在答案中加了一点。 – BeetleJuice