2016-10-23 34 views
0

如何在ajax請求數據到達後單獨渲染模板?加載模板後可以加載數據嗎?

在版本中我有一個ajax請求和請求如何延遲,窗體加載沒有數據。數據加載延遲幾秒鐘。

這種行爲不雅

@Component({ 
    providers: [CompanyService], 
    templateUrl:'<input type="text" id="address" name="address" [(ngModel)]="company.address" #address="ngModel" >' 
}) 

export class FormComponent { 

    private company:Company = new Company(); 
    private acao:String = null; 

    constructor(private companyService:CompanyService) { 

     this.route.params.subscribe(params => { 

      if (params['id'] !== undefined) { 
       this.companyService.getById(params['id']).subscribe(result => this.company = result); 
       this.acao = 'edit'; 
      } 
     }); 
    } 

我簡化代碼更好的視覺效果。

回答

1

您可以使用界面Resolve of Angular 2解決此問題。使用界面解決方法將在模板之前調用解決方法。

關注...

在form.component首次進口:

import {Router, ActivatedRoute, Resolve, 
    ActivatedRouteSnapshot} from '@angular/router'; 

然後實現在form.component接口:

export class FormComponent implements OnInit, Resolve<Company> { 

然後創建form.component方法:

resolve(route: ActivatedRouteSnapshot): Promise<Company>|boolean { 

     return new Promise((resolve, reject) => { 

      if (route.params['id'] !== undefined) { 
       this.companyService.getById(route.params['id']) 
        .subscribe(result => { 

         result = false; 

         if (result) { 
          return resolve(result); 
         } else { 
          return false; 
         } 

        }); 
       this.acao = 'edit'; 
      } 
     }); 
    } 


    ngOnInit(){ 

     this.company.address = this.route.snapshot.data['data']; 
    } 

然後添加你的路由文件:

path: 'edit/:id', component: FormComponent, 
resolve: { data: FormComponent } 

終於改變你的模塊添加供應商:

@NgModule({ 
    imports: [... ], 
    declarations: [ ... ], 
    providers:[ FormComponent ] 
}) 

//it is necessary to inform all dependent services 

這將很好地工作。