Jobsdev
Jobsdev

Reputation: 1039

Is it possible to load the data after loading the template?

how to render the template solely after the data arrival of ajax request?

in the edition i have an ajax request and how the request delay, the form is loaded without the data. 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.

Upvotes: 0

Views: 347

Answers (1)

Renato Souza de Oliveira
Renato Souza de Oliveira

Reputation: 4574

you can solve this with the interface Resolve of Angular 2. using the interface solves the method resolves will be called before the template.

Follow...

first import in form.component:

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

then implements the interface in form.component:

export class FormComponent implements OnInit, Resolve<Company> { 

Then create methods in 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.

Upvotes: 1

Related Questions