angular2firebase - multiple instances using Angular 6

☆樱花仙子☆ 提交于 2019-12-10 12:17:27

问题


I'm upgrading to Angular 6 using AngularFire2. My app referenced 2 Firebase projects using code like this to create the database reference:

public initFirebaseApp(config: FirebaseAppConfig, firebaseAppName: string) {
        this._db = new AngularFireDatabase(_firebaseAppFactory(config, firebaseAppName));
    }

This code is now broken. I get this:

ERROR in src/app/services/firebase.service.ts(24,25): error TS2554: Expected 5 arguments, but got 1.

Thanks!


回答1:


AngularFire now support many more configuration objects via Injection now, which is why it's expecting more arguments. It currently takes:

constructor(
  @Inject(FirebaseOptionsToken) options:FirebaseOptions,
  @Optional() @Inject(FirebaseNameOrConfigToken) nameOrConfig:string|FirebaseAppConfig|undefined,
  @Optional() @Inject(RealtimeDatabaseURL) databaseURL:string,
  @Inject(PLATFORM_ID) platformId: Object,
  zone: NgZone
)

Though now that we support dependency injection, I wouldn't suggest directly initializing like you are to support multiple apps. We have an open issue for documenting this but you can now inject different FirebaseOptions via the FirebaseOptionsToken into different components, if you need multiple databases in the same component use something like this:

@Injectable()
export class AngularFireDatabaseAlpha extends AngularFireDatabase { }

@Injectable()
export class AngularFireDatabaseBeta extends AngularFireDatabase { }


export function AngularFireDatabaseAlphaFactory(platformId: Object, zone: NgZone): Project1AngularFireAuth {
  return new AngularFireDatabaseAlpha(environment.firebase[0], 'alpha', undefined, platformId, zone)
}
export function AngularFireDatabaseBetaFactory(platformId: Object, zone: NgZone): Project2AngularFireAuth {
  return new AngularFireDatabaseBeta(environment.firebase[1], 'beta', undefined, platformId, zone)
}


@NgModule({
  ...,
  providers: [
    ...,
    { provide: AngularFireDatabaseAlpha, deps: [PLATFORM_ID, NgZone], useFactory: AngularFireDatabaseAlphaFactory },
    { provide: AngularFireDatabaseBeta, deps: [PLATFORM_ID, NgZone], useFactory: AngularFireDatabaseBetaFactory },
    ...
  ],
  ...
})

Then you can just rely on Dependency Injection to get AngularFireDatabaseAlpha and AngularFireDatabaseBeta into your component.



来源:https://stackoverflow.com/questions/50473945/angular2firebase-multiple-instances-using-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!