离子 3 angularfire2 代码到离子 4 angularfire2 代码

ionic 3 angularfire2 code to ionic 4 angularfire2 code

我的代码与 ionic 3 angular 5 的工作方式如下

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)
          }
        )
      })
  }

然而,对于 ionic 4 .map 不再起作用。我如何转换此代码?

如你所见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.

所以现在您可以像这样使用 map()

// 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)
                }
            )
    })
}

与问题本身无关,但以防万一,如果您希望 getUser() 方法成为 return 一个承诺,您也可以使用 RXJS 运算符(而不是创建和解决一个承诺),像这样:

// 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()
}