Reputation: 489
I am making my first angular2 app.
It gets login verification from the server. It posts username (email) and password to the server and in return it gets the USER OBJECT.
user.ts
export class User {
constructor(
public id: number,
public email: string,
public password: string,
public token: string,
public firstName: string,
public lastName: string,
public lastLogin: number,
public credits: number,
public isAdmin: number
) { }
}
Success json
{"id":2,"email":"john.doe@google","password": "", "token":"37ee4a596d443aaf0308c0783bfdcf83","firstName":"John","lastName":"Doe","lastLogin":1486994085,"credits":0,"isAdmin":0}
Failure messages
{"code":"empty","error":"Password is empty"}
{"code":"auth-failed","error":"Login information not correct"}
{"code":"auth-failed","error":"Invalid id\/token, please login again"}
Now when went to program my failure messages it got me thinking
My code is this, how will i handle failure in the angular2
return this.http.get(url)
.map(response => response.json() as User)
.catch(this.handleError);
I guess I cannot use the response.json() as User cause it will crash app in case of error. What is the best practice? Should i change my json format for success also ?
Upvotes: 2
Views: 107
Reputation: 2327
First, you should make sure you have the correct HTTP status code set on the response from the server (assuming you control the server). Then, you can set the content of the response to be whatever you want and then handle it however you like based on the status using the catch handler.
return this.http.get(url)
.map(response => response.json() as User)
.catch(err => /* handle err*/);
More info on status codes:
If the server isn't setting the status codes, then you'd have to look at the raw data to see what you're getting (edit: hopefully this isn't the case as your server wouldn't be following the rules).
https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Upvotes: 1
Reputation: 3753
Just use res.json()
Like this:
login(){
return this.http.get(url)
.map(response => response.json());
}
Then for your function calling this http request like this:
this._yourservice.login().subscribe(
suc => {
console.log(suc); // success json, if returned with http response status 200
},
err => {
var res = JSON.parse(err._body);
console.log(suc); // error json if returned with other http response status
}
);
Upvotes: 1
Reputation: 22001
If you return Http status codes other than 200 as part of the server response, then the angular 2 call to http.get
will throw an exception, directing you handleError
.
Upvotes: 0