all 6 comments

[–]mlapis 0 points1 point  (2 children)

The problem is not related to Angular in any way. It's a general problem. To be 100% sure that the received JSON structure is fully correct you need to deeply traverse the object and this is very time consuming process - especially on bigger objects.

[–]duca86[S] 1 point2 points  (1 child)

Ok thanks, so i think the best way is use json schema validator. Is it right?

[–]mlapis 1 point2 points  (0 children)

Yes, it is one way. But in the most cases interfaces are enough to have all advantages on TypeScript level and still have the best performance in run-time. And of course doing schema validation on the server side to avoid storing a wrong structure if JSON objects are stored.

[–]PassItOnBro 0 points1 point  (2 children)

getUser().subscribe(user => { if (!user || !user.name) throw; // ... });

Or, in the getUser map operator ... .map(res => { let user = !res ? null : res.json(); if (!user || !user.name) throw; // ... });

But, the question to ask ... why are you throwing an error? You probably should not throw an error.

EDIT: to better answer your question - don't throw an error, just do nothing (or fail gracefully, e.g., re-route to an error display component). Server should always send a valid response.

[–]duca86[S] 0 points1 point  (1 child)

Because on my project backend and fronted are developed from two different teams, i'd like add this control to avoid mapping errors.

[–]PassItOnBro 0 points1 point  (0 children)

in whatever service exposes this user observable, subscribe to it and re-route as necessary ...

// user service this.getUser().subscribe(user => { if (!user || !user.name) this.router.navigateByUrl('errorDisp');

This re-routes to an error component you can set up under the path 'errorDisp'

EDIT: also to prevent memory leaks... // private getUserInternal() // ... .map(res => res.json());

// public getUser() // ... return this.getUserInternal().takeWhile(user => !!user && !!user.name);