如何在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';
}
});
}
我简化了代码以便更好地查看。
答案 0 :(得分:1)
你可以通过Angular 2的Resolve接口来解决这个问题。 使用接口解决方法将在模板之前调用resolve。
请...
首先在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
这将很有效。