Search code examples
elasticsearchangularloopback

How to use promise with angular 2 and loopback?


Here shows the project done in angular2 framework with loopback. I want to use promise along with data retrieved using loopback.

data.component.ts

ngOnInit () {
this.dataService.getAllData()
.then(response => {this.data.push(response);});
}

data.service.ts

public getAllData(): any {
    this.my_model.find()
    .toPromise()
    .then((res : Response) => res);

}

I want to interpolate this data to the html view. How to do this?


Solution

  • You're not returning a Promise in your getAllData(). You could try it like this:

    data.service.ts

    public getAllData(): any {
        return this.my_model.find().toPromise();
    }
    

    data.component.ts

    ngOnInit () {
        this.dataService.getAllData()
        .then(response => { this.data.push(response); });
    }
    

    and somewhere in your template you can use this array:

    <div *ngFor="let item of data">
        <span>{{ item.id }}</span>
    </div>