【问题标题】:Can't seem to add a Service as provider to app.component.ts似乎无法将服务作为提供者添加到 app.component.ts
【发布时间】:2018-08-06 05:54:34
【问题描述】:

我需要添加提供程序以与 app.component.ts 共享变量,因为我正在我的应用程序中实时查找记录的用户数据,但我似乎无法将提供程序添加到构造函数,我不断收到以下错误。

Firebase:没有创建 Firebase 应用“[DEFAULT]” - 调用 Firebase App.initializeApp()

这是我的代码的快照:

app.component.ts :

import { UsersServiceProvider } from '../providers/users-service/users-service';
@Component({
  templateUrl: 'app.html',
})

export class MyApp {
    @ViewChild(Nav) navCtrl: Nav;
    rootPage:any = InicioPage;

    constructor(public userServices : UsersServiceProvider) //another imports too
    platform.ready().then(() => {
      statusBar.styleDefault();
      splashScreen.hide();
    });
    var config = {
         //some config for app and firebase
    };
    firebase.initializeApp(config);
    var that = this;
    firebase.auth().onAuthStateChanged((user) => {
        if (user) {
        // Need to set variable on userServices HERE
        }
    })
};

用户服务.ts

import { Injectable } from '@angular/core';
import {AlertController , Platform} from 'ionic-angular'
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import * as firebase from 'firebase';

@Injectable()
export class UsersServiceProvider {

public currentUser : any;
 constructor(private platform: Platform, public alertCtrl: AlertController, public http: Http) {
}

setCurrentUser(user){
  this.currentUser = user; // WANT TO SET IT HERE
}

}

app.module.ts 一切正常

【问题讨论】:

    标签: angular typescript firebase ionic2


    【解决方案1】:

    这是你如何从MyApp 调用UsersServiceProvidersetCurrentUser() 方法:

    this.userServices.setCurrentUser(user);
    

    这里是上下文

    import {
      UsersServiceProvider
    } from '../providers/users-service/users-service';
    @Component({
      templateUrl: 'app.html',
    })
    
    export class MyApp {
      @ViewChild(Nav) navCtrl: Nav;
      rootPage: any = InicioPage;
    
      constructor(public userServices: UsersServiceProvider) //another imports too
      platform.ready().then(() => {
        statusBar.styleDefault();
        splashScreen.hide();
      });
      var config = { //some config for app and firebase
      };
      firebase.initializeApp(config);
      var that = this;
      firebase.auth().onAuthStateChanged((user) => {
        if (user) {
          this.userServices.setCurrentUser(user); // Need to set variable on userServices HERE
        }
      })
    };
    

    【讨论】:

    • 我真的很想调用 setCurrentUser,但我无法将提供程序添加到构造函数中,因为我在 firebase 中遇到了描述的错误:(
    【解决方案2】:

    我不熟悉 Firebase,但您是否尝试在 app.module.ts 中添加该服务?您必须先这样做,然后才能将其注入任何课程。它应该是这样的:

    @NgModule({
    declarations: [],
    imports: [],
    providers: [UsersServiceProvider]
    }) 
    

    【讨论】:

      猜你喜欢
      • 2016-12-08
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 2016-02-14
      • 1970-01-01
      相关资源
      最近更新 更多