2016-10-23 37 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 

这将很好地工作。