也可以
我需要添加提供商以与app.component.ts共享变量,因为我在应用程序中实时寻找已记录的用户数据,但是我无法似乎要将提供商添加到构造函数,我不断收到以下错误。
firebase:未创建firebase应用程序'[默认]' - 致电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
}
})
};
用户服务
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
这是您从 MyApp
:
UsersServiceProvider
的setCurrentUser()
方法的方式 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
}
})
};
我不熟悉firebase,但是您是否尝试在app.module.ts中添加服务?您必须这样做,然后才能将其注入任何班级。它应该喜欢这样:
@NgModule({
declarations: [],
imports: [],
providers: [UsersServiceProvider]
})