Last active
October 19, 2015 16:48
-
-
Save mpavel/5578038e04447482b99e to your computer and use it in GitHub Desktop.
Get more items - ng2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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