1
\$\begingroup\$

I have a registration form. Step 1 user creates an account. As user creates an account I need to authenticate user with the created account.

in my account.service.ts I have following.

Is this the best way to handle this? and how can improve this to handle errors from 2 different http calls?

 public createAccount(reg: CreateUserRequestModel): Observable<any> {
 return this.apiService.post('api/register/account', reg)
 .flatMap(()=>{
 return this.authenticationService.authenticate(reg.emailAddress, reg.password)
 }).map((response)=>{
 return response.json()
 })
 .catch((error: any) => {
 return Observable.throw(error.json());
 });
 }
200_success
145k22 gold badges190 silver badges478 bronze badges
asked May 24, 2017 at 9:55
\$\endgroup\$
1
  • \$\begingroup\$ You can remove code blocks and return of arrow functions. .flatMap(() => this.authenticationService.authenticate(reg.emailAddress, reg.password)).map(response => response.json()).catch((error: any) => Observable.throw(error.json()); \$\endgroup\$ Commented May 24, 2017 at 9:59

1 Answer 1

1
\$\begingroup\$
public createAccount(registrationRequest: CreateUserRequestModel): Observable<SomeType> {
 return this.apiService.post('api/register/account', registrationRequest)
 .flatMap(() => this.authenticationService.authenticate(registrationRequest.emailAddress, registrationRequest.password))
 .map(response => <SomeType>response.json())
 .catch(error => Observable.throw(error.json()));
}
  • @Tushar made a good point on code compactness, which can be applied to all arrow functions in the code.
  • TypeScript is about types. Try to not use any in return type definitions. Do define some return type and cast the result to it (see SomeType).
  • I'm not sure if you really want to do .catch(error => Observable.throw(error.json())) where it happens now or move it to the consumers side (e.g. .subscribe(() => {...}, error => this.handle(error))
  • reg is a bad name. Spell things out.
answered May 25, 2017 at 16:46
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.