You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Tutorial example has a problem to enter new item into an empty list #22120
protectedisCollectionIdNumeric<Textends{id: any}>(collection: T[],collectionName: string): boolean{// collectionName not used now but override might maintain collection type information// so that it could know the type of the `id` even when the collection is empty.return!!(collection&&collection[0])&&typeofcollection[0].id==='number';}
Suggested fix: override the genId method as we know a Hero should always have an id:
genId(heroes: Hero[]): number {returnheroes.length>0 ? Math.max(...heroes.map(hero=>hero.id))+1 : 1;}
import{InMemoryDbService}from'angular-in-memory-web-api'import{Hero}from'./hero'exportclassInMemoryDataServiceimplementsInMemoryDbService{createDb(){constheroes=[{id: 11,name: 'Mr. Nice'},{id: 12,name: 'Narco'},{id: 13,name: 'Bombasto'},{id: 14,name: 'Celeritas'},{id: 15,name: 'Magneta'},{id: 16,name: 'RubberMan'},{id: 17,name: 'Dynama'},{id: 18,name: 'Dr IQ'},{id: 19,name: 'Magma'},{id: 20,name: 'Tornado'},]return{ heroes }}// Overrides the genId method to ensure that a hero always has an id.// If the heroes array is empty,// the method below returns the initial number (11).// if heroes array is not empty, the method below returns the highest// hero id + 1.genId(heroes: Hero[]): number{returnheroes.length>0 ? Math.max(...heroes.map(hero=>hero.id))+1 : 11}}
Activity
trotyl commentedon Feb 10, 2018
Nice catch, currently the
in-memory-dbwould only auto-increase theidwhen there's existingidproperty and they're numeric:Suggested fix: override the
genIdmethod as we know aHeroshould always have anid:Demo here.
FumioNonaka commentedon Feb 10, 2018
Thank you for your suggestion. I appended the solution to my article.
avi182 commentedon Mar 12, 2018
How can i check which method is responsible for the id generating?
jenniferfell commentedon Apr 25, 2018
docarea=tutorial
robphoenix commentedon Sep 7, 2018
For anyone else with the same problem that finds this issue, the
genId()method should be added into thein-memory-data.service.tsfile, there's a gist here - https://gist.github.com/robphoenix/3767cf08772347e02c2434bcf3b84635sreevani-ship-it commentedon Oct 8, 2018
Fixed as part of PR #24445
angular-automatic-lock-bot commentedon Sep 14, 2019
This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.
Read more about our automatic conversation locking policy.
This action has been performed automatically by a bot.