简体   繁体   English

加载模板后是否可以加载数据?

[英]Is it possible to load the data after loading the template?

how to render the template solely after the data arrival of ajax request? 如何仅在ajax请求的数据到达后呈现模板?

in the edition i have an ajax request and how the request delay, the form is loaded without the data. 在该版本中,我有一个ajax请求以及请求如何延迟,该表单不包含数据。 The data loads with a few seconds delay. 数据加载会延迟几秒钟。

this behavior is inelegant 这种行为是不雅的

@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';
            }
        });
    }

I simplify the code for better viewing. 我简化了代码以更好地查看。

you can solve this with the interface Resolve of Angular 2. using the interface solves the method resolves will be called before the template. 您可以使用Angular 2的Resolve接口解决此问题。使用接口resolve方法将在模板之前调用resolve方法。

Follow... 跟随...

first import in form.component: 首先导入form.component:

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

then implements the interface in form.component: 然后在form.component中实现接口:

export class FormComponent implements OnInit, Resolve<Company> { 

Then create methods in form.component: 然后在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'];
    }

then add on your route file: 然后添加您的路由文件:

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

and finally change you module adding providers: 最后更改您的模块,添加提供程序:

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

//it is necessary to inform all dependent services  

this will work well. 这将很好地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM