angular - How to map object array to my type array -


i have class:

export class    stuff {       id: string;       namd: string;     } 

with angular < 4.3 have call:

getstuff(): observable<stuff[]> {     return this.http.get('api-url-here/stuff')         .map((data: response) => {             return data.json()                 .map((item: any) => {                     return {                     id: item.id,                     name: item.name                 };         });     }) } 

with angular >= 4.3 changed this:

getstuff(): observable<stuff[]> {     return this.http.get<stuff[]>('api-url-here/stuff')         .map((data: any) => {             return data                 .map((item: any) => {                     return {                     id: item.id,                     name: item.name                 };         });     }) } 

i receiving array of stuff fro api looking that.

[  {"id":1,"name": "name" } ] 

as can see code example above have map data twice type shape (stuff[]). there better way of doing angular 4.3+ ?

you using typed response in new httpclientmodule, in first map result parsed.

getstuff(): observable<stuff[]> {   return this.http.get<stuff[]>('api-url-here/stuff'); } 

should work. , then

somestaffservice.getstuff().subscribe(staff => console.log(staff)); 

update:

in case able handle errors in 2 ways. outside of service

somestaffservice.getstuff().subscribe(   staff => console.log(staff),   (err: httperrorresponse) => {     if (err.error instanceof error) {       console.log("client-side error occured.");     } else {       console.log("server-side error occured.");     }   } ); 

or can subscribe right in service , catch error there. please refer documentation


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -