Skip to content

Instantly share code, notes, and snippets.

@mpavel
Last active Oct 19, 2015
Embed
What would you like to do?
Get more items - ng2
// This is my Angular2 Component
class ItemList {
offset = 0;
items:ListItem[] = [];
// inject MyApi and set it as a private property on the class, automatically
// then get the initial items by default
constructor(private api:MyApi) {
this.getNextItems();
}
getNextItems() {
this.api.getItemList(this.offset).then((new_items) => {
// When you use the wrong syntax, of course it will not work! Below is the correct way of adding elements
this.items.push.apply(this.items, new_items);
// Updating the offset of the list to reuse on the next request
this.offset += this.items.length;
});
}
}
@Injectable()
class MyApi {
getItemList(offset:number):Promise<ListItem[]> {
return window.fetch(`/api/items/?&offset=${offset}`)
.then((response) => response.json())
.then((data) => {
return data.map(item => this.parseListItemData(item));
});
}
private parseListItemData(listItemData):ListItem {
return new ListItem(listItemData);
}
}
// Model classes
class BaseItem {
rawData:Object;
id:string;
title:string;
description:string;
constructor(serverItem) {
this.rawData = serverItem;
this.id = serverItem.id;
this.title = serverItem.title;
this.description = serverItem.description;
}
}
class ListItem extends BaseItem {
constructor(serverItem) {
super(serverItem);
}
}
class Item extends BaseItem {
constructor(serverItem) {
super(serverItem);
// plus some other properties here...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment