启动应用程序时出现错误“未捕获(承诺):首先运行init()!”。我猜该错误是由 ngOnInit()中的firebase组件引起的 这是我的代码
import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from "@angular/core";
import { Observable } from 'rxjs/Observable';
import { BackendService, FirebaseService } from "../services";
import { ListView } from 'ui/list-view';
import { TextField } from 'ui/text-field';
import { ScrollView } from 'ui/scroll-view';
@Component({
moduleId: module.id,
selector: "chat-tab",
templateUrl: "chat.tab.component.html",
styleUrls: ["chat.tab.component.css"]
})
export class ChatTabComponent implements OnInit {
public constructor(
private firebaseService: FirebaseService
) { }
ngOnInit() {
this.me = BackendService.token;
this.chats$ = <any>this.firebaseService.getChats();
}
public me: String;
@ViewChild("list") lv: ElementRef;
@ViewChild("textfield") tf: ElementRef;
list: ListView;
textfield: TextField;
public chats$: Observable<any>;
public ngAfterViewInit() {
this.list = this.lv.nativeElement;
this.textfield = this.tf.nativeElement;
}
scroll(count:number){
console.log("scrolling to ", count)
this.list.scrollToIndex(count-1);
this.list.refresh();
}
chat(message: string) {
this.firebaseService.chat(message).then((data: any) => {
let count = this.list.items.length;
this.scroll(count);
});
this.textfield.text = '';
}
filter(sender) {
if (sender == BackendService.token) {
return "me";
}
else {
return "them"
}
}
align(sender) {
if (sender == BackendService.token) {
return "right"
}
else {
return "left"
}
}
showImage(sender) {
if (sender == BackendService.token) {
return "collapsed"
}
else {
return "visible"
}
}
}
这是firebase.service
import {Injectable, NgZone} from "@angular/core";
import {User, Yowl} from "../models";
import { BackendService } from "./backend.service";
import firebase = require("nativescript-plugin-firebase");
import {Observable} from 'rxjs/Observable';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/share';
@Injectable()
export class FirebaseService {
constructor(
private ngZone: NgZone,
){}
yowls: BehaviorSubject<Array<Yowl>> = new BehaviorSubject([]);
private _allYowls: Array<Yowl> = [];
chats: BehaviorSubject<Array<Yowl>> = new BehaviorSubject([]);
private _allChats: Array<Yowl> = [];
getMessage(){
firebase.addOnMessageReceivedCallback(function (data ){
alert(JSON.stringify(data));
})
}
register(user: User) {
return firebase.createUser({
email: user.email,
password: user.password
}).then(
function (result:any) {
return JSON.stringify(result);
},
function (errorMessage:any) {
alert(errorMessage);
}
)
}
login(user: User) {
return firebase.login({
type: firebase.LoginType.PASSWORD,
passwordOptions: {
email: user.email,
password: user.password
}
}).then((result: any) => {
BackendService.token = result.uid;
return JSON.stringify(result);
}, (errorMessage: any) => {
alert(errorMessage);
});
}
logout(){
BackendService.token = "";
firebase.logout();
}
resetPassword(email) {
return firebase.resetPassword({
email: email
}).then((result: any) => {
alert(JSON.stringify(result));
},
function (errorMessage:any) {
alert(errorMessage);
}
).catch(this.handleErrors);
}
getYowls(): Observable<any> {
return new Observable((observer: any) => {
let path = 'Yowls';
let onValueEvent = (snapshot: any) => {
this.ngZone.run(() => {
let results = this.handleSnapshot(snapshot.value);
observer.next(results);
});
};
firebase.addValueEventListener(onValueEvent, `/${path}`);
}).share();
}
handleSnapshot(data: any) {
//empty array, then refill and filter
this._allYowls = [];
if (data) {
for (let id in data) {
let result = (<any>Object).assign({id: id}, data[id]);
this._allYowls.push(result);
}
this.publishUpdates();
}
return this._allYowls;
}
getChats(): Observable<any> {
return new Observable((observer: any) => {
let path = 'Chats';
let onValueEvent = (snapshot: any) => {
this.ngZone.run(() => {
let results = this.handleChatSnapshot(snapshot.value);
observer.next(results);
});
};
firebase.addValueEventListener(onValueEvent, `/${path}`);
}).share();
}
handleChatSnapshot(data: any) {
//empty array, then refill and filter
this._allChats = [];
if (data) {
for (let id in data) {
let result = (<any>Object).assign({id: id}, data[id]);
this._allChats.push(result);
}
this.publishChatUpdates();
}
return this._allChats;
}
sendYowl(Yowl:any) {
let yowl = Yowl;
return firebase.push(
"/Yowls",
{ "name": "Mr. Growlllr", "username": "MrGrwwlr", "text": "Yooowwwwlll!", "UID": BackendService.token, "date": 0 - Date.now()}
).then(
function (result:any) {
return 'Yowwled!';
},
function (errorMessage:any) {
console.log(errorMessage);
});
}
chat(message:string) {
//let chat = Chat;
console.log(message)
return firebase.push(
"/Chats",
{ "message": message, "to": "MrGrwwlr", "from": BackendService.token, "date": 0 - Date.now()}
).then(
function (result:any) {
return "chatted";
},
function (errorMessage:any) {
console.log(errorMessage);
});
}
publishUpdates() {
this._allYowls.sort(function(a, b){
if(a.date < b.date) return -1;
if(a.date > b.date) return 1;
return 0;
})
this.yowls.next([...this._allYowls]);
}
publishChatUpdates() {
this._allChats.sort(function(a, b){
if(a.date > b.date) return -1;
if(a.date < b.date) return 1;
return 0;
})
this.chats.next([...this._allChats]);
}
handleErrors(error) {
console.log(JSON.stringify(error));
return Promise.reject(error.message);
}
}
这是app.component.ts文件,它工作正常,没有任何错误,但可能丢失了一些东西
import { Component, OnInit } from "@angular/core";
const firebase = require("nativescript-plugin-firebase");
const dialogs = require("ui/dialogs");
import { BackendService } from "./services/backend.service";
@Component({
selector: "main",
template: "<page-router-outlet></page-router-outlet>"
})
export class AppComponent implements OnInit {
ngOnInit(): void {
firebase.init({
/*onPushTokenReceivedCallback: function(token) {
alert("Firebase push token: " + token);
},*/
onMessageReceivedCallback: function(message) {
dialogs.alert({
title: "Push message: " + (message.title !== undefined ? message.title : ""),
message: JSON.stringify(message.body),
okButtonText: "W00t!"
});
},
//persist should be set to false as otherwise numbers aren't returned during livesync
persist: false,
//storageBucket: 'gs://yowwlr.appspot.com',
onAuthStateChanged: (data: any) => {
if (data.loggedIn) {
BackendService.token = data.user.uid;
}
else {
BackendService.token = "";
}
}
}).then(
function (instance) {
console.log("firebase.init done");
},
function (error) {
console.log("firebase.init error: " + error);
}
);
}
}
答案 0 :(得分:0)
您是否已在app.ts文件中添加了firebase初始化方法。如果未将以下代码粘贴到app.ts文件中。
`const firebase = require("nativescript-plugin-firebase");`
`firebase.init({
// Optionally pass in properties for database,
authentication and cloud messaging,
// see their respective docs.
}).then(
instance => {
console.log("firebase.init done");
},
error => {
console.log(`firebase.init error: ${error}`);
}
);
`
答案 1 :(得分:0)
我不知道什么是角度解决方案
但是我正在将vue js与本机脚本一起使用
使用this。$ nextTick() 为我工作 可能有一些与角度有关的东西
我的代码
var _this = this
this.$nextTick(() => {
firebase.getValue('path')
.then(result => {
console.log('result:',result)
})
.catch(error => console.log("Error: " + error))
});