Vik
Vik

Reputation: 9289

ionic 3 angularfire2 code to ionic 4 angularfire2 code

i have my code with ionic 3 angular 5 working as below

getUser(uid:string){
    console.log('start of getUser with uid:' + uid)
    return new Promise((resolve, reject) =>
      {
        this.db.object("/users/" + uid).snapshotChanges().map(
          (snapshot) => {return snapshot.payload.val()}
        ).subscribe(
          res => {
            console.log('response:' + res)
            resolve(res)
          },
          err => {
            console.log(err)
            reject(err)
          }
        )
      })
  }

however, with ionic 4 .map does not work any more. how do i convert this code?

Upvotes: 1

Views: 40

Answers (1)

sebaferreras
sebaferreras

Reputation: 44659

Just like you can see here

Starting in version 5.5 we have shipped "pipeable operators", which can be accessed in rxjs/operators (notice the pluralized "operators"). These are meant to be a better approach for pulling in just the operators you need than the "patch" operators found in rxjs-compat package.

NOTE: Using rxjs or rxjs/operators without making changes to your build process can result in larger bundles.

So now you can use map() like this:

// RxJS
import { map } from 'rxjs/operators/map';

// ...

getUser(uid:string){
    console.log('start of getUser with uid:' + uid)
    return new Promise((resolve, reject) => {
        this.db.object("/users/" + uid)
            .snapshotChanges()
            .pipe(
                map((snapshot) => {
                    return snapshot.payload.val();
                })
            )
            .subscribe(
                res => {
                    console.log('response:' + res)
                    resolve(res)
                },
                err => {
                    console.log(err)
                    reject(err)
                }
            )
    })
}

Not related to the question itself but just in case, if you want your getUser() method to return a promise, you can use RXJS operators as well (instead of creating and resolving a promise), like this:

// RxJS
import { map } from 'rxjs/operators/map';
import { tap } from 'rxjs/operators/tap';   

// ...

public getUser(uid: string): Promise<any> {
    console.log('start of getUser with uid:' + uid)

    return this.db
        .object("/users/" + uid)
        .snapshotChanges()
        .pipe(
            map((snapshot) => {
                return snapshot.payload.val();
            }),
            tap((response) => {
                console.log('response:' + response);
            })
        )
        .toPromise()
}

Upvotes: 1

Related Questions