I get Uncaught (in promise): Run init() first! error when i lunch my app


#1

i guess the error is caused by the firebase component inside the ngOnInit()
here is my code

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"

        }

    }



}

and this is the 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);

  }

}

#2

As the error says, you have to call the .init(YourParams) method before using any other apis / methods in firebase. Refer the plugin docs for more info.


#3

@manojdcoder i already did that


#4

I don’t see init in your code.


#5

i run the intit in app.ts file


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

        }

    );

  }

}








#6

Try commenting out

 this.chats$ = <any>this.firebaseService.getChats();

Make sure it runs after init is completed.


#7

am sorry but ,comment it where exactly cause i already have it inside the ngOnInit that belongs to the chat,ts fille


#8

anything new about this topic? @manojdcoder