How to do the Flattening in Rxjs for Angular Auth Service?

Viewed 68

I have created a Authentication service in Angular with function SignUp that sends the API Request to Firebase, As Firebase returns the User ID, I am saving the userid into my personal MongoDB Database with its Role. Now the problem here is i am sending two request which i want to further Subscribed in Register.component.ts, I am not able to understand how to achieve this. Below are the sample code that i have tried.

auth.service.ts

 signUp(email: string, password: string) {

return this.http.post<AuthResponse>(`https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=${config.API_KEY}`, {
  email: email,
  password: password,
  returnSecureToken: true
}).pipe(
  switchMap(data => { 

    return  this.http.post<any>(`${config.BASE_URL}/api/ezusers/`,{useruid: data.idToken, 'isRegistered':false}); // or this.userId
  })
).map(response => {
this.authenticatedUser(response.email, response.localId, response.idToken, +response.expiresIn);
  // this.userOrders = response;
  return
});

}

Register.component.ts

onSubmit() {
this.loading = true;
if (this.registerForm.valid) {
  this._authService.signUp(this.registerForm.value.email, this.registerForm.value.password).subscribe(
    res => {
      console.log(res);
      this.loading = false;
      this.registerForm.reset();
      this.success = true;
      this.error = false;

    },
    err => {
      console.log(err);
      this.loading = false;
      this.success = false;
      this.error = this.errMsgs[err.error.error.message];

    })



}
else {

}

}

Any help would be really Appreciated.

Thanks in Advance!

1 Answers

I'm not totally understand what you want to achieve in register component, but what's I've noticed there always response will be falsy, as you return undefined in service. Not sure what method authenticatedUser returns, but try it.

signUp(email: string, password: string) {

return this.http.post<AuthResponse>(`https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=${config.API_KEY}`, {
  email: email,
  password: password,
  returnSecureToken: true
}).pipe(
  switchMap(data => { 

    return  this.http.post<any>(`${config.BASE_URL}/api/ezusers/`,{useruid: data.idToken, 'isRegistered':false}); // or this.userId
  })
).map(response => 
this.authenticatedUser(response.email, response.localId, response.idToken, +response.expiresIn)
);
Related