3
votes

In my app.component.ts, the am using this function to register the user onto firebase using angularFire2. However I am getting an error with "property 'subscribe' does not exist on type 'void".

register() {
    this.userService.registerUser(this.model)
        .subscribe(
            data => {
                console.log('Registration successful')
            },
            error => {
                this.loading = false;
            });
}

and in my userService.ts, I have the following call getting data from firebase

registerUser(user: User) {
    this.angularFire.auth.createUser({
    email: user.email,
    password: user.password
    }).then(
    (success) => {
        console.log(success);
    }).catch(
    (err) => {
        console.log(err);
    })
}

I do understand why the error appears. Because my registerUse function in the userService does not return an observable. As I am new to typescript, how can I change that to become an observable such that I can console.log('Success') in the app.component.ts when the data comes back?

1

1 Answers

6
votes

The most straightforward option would be to return the promise:

import { FirebaseAuthState } from 'angularfire2';

registerUser(user: User): Promise<FirebaseAuthState> {
  return this.angularFire.auth.createUser({
    email: user.email,
    password: user.password
  })
  .then((authState: FirebaseAuthState) => {
    console.log(success);
    return authState;
  })
  .catch((error) => {
    console.log(error);
    throw error;
  });
}

However, it you want to return an observable, you can use fromPromise:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromPromise';
import { FirebaseAuthState } from 'angularfire2';

registerUser(user: User): Observable<FirebaseAuthState> {
  return Observable.fromPromise(this.angularFire.auth.createUser({
    email: user.email,
    password: user.password
  })
  .then((authState: FirebaseAuthState) => {
    console.log(success);
    return authState;
  })
  .catch((error) => {
    console.log(error);
    throw error;
  }));
}

If you are going use a catch in registerUser to log the error, you should re-throw the error so that it can be caught and handled by the caller. If you don't need the logging, just leave it out and the caller can handle any errors (via the observable):

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromPromise';
import { FirebaseAuthState } from 'angularfire2';

registerUser(user: User): Observable<FirebaseAuthState> {
  return Observable.fromPromise(this.angularFire.auth.createUser({
    email: user.email,
    password: user.password
  }));
}

If you don't want to return AngularFire2's FirebaseAuthState, you can use a then to return something else as the promise's resolved value (which will be the value emitted by the observable).