I'm not able to subscribe to a topic, below my app.ts excerpt
import "./bundle-config";
import * as app from 'application';
import * as firebase from "nativescript-plugin-firebase";
firebase.init({
onMessageReceivedCallback: (message: firebase.Message) => {
console.log(`Title: ${message.title}`);
console.log(`Body: ${message.body}`);
// if your server passed a custom property called 'foo', then do this:
console.log(`value of 'foo': ${message.data.foo}`);
}
}).then(
instance => {
console.log(`firebase.init done !! [${instance}]`);
firebase.subscribeToTopic("/topics/musa-news").then(
(value) => console.log("sub ok:", value),
(reason) => console.log("sub err:", reason)
);
},
error => {
console.log(`firebase.init error: ${error}`);
}
);
In the console I got:
JS: sub err: Can be run only after init
Probably I don't understand when it is safe to call subscribeToTopic, the message says after init but apparently the init then() context is not such place.
I had the same problem, I did some research and I found out that "firebase.instance" is null and that was caused by "com.google.firebase.database" being undefined.
How i fixed it
I edited the nativescript.firebase.json and set "realtimedb" to true, after that it worked!
Thank you @fabsch412, you made my day!
For me, file was firebase.nativescript.json located at the root folder of project and editing it didn't work.
How I fixed it:
cd <root of your project>
cd node_modules/nativescript-plugin-firebase
npm run config
<this time be sure to enable Real time database>
cd <root of your project>
tns platform remove android
tns run anroid
You can check if firebase instance exists with:
firebase.init(
{
onPushTokenReceivedCallback: function(token) {
console.log("app.js => onPushTokenReceivedCallback - Firebase plugin received a push token: " + token);
},
onMessageReceivedCallback: function(message) {
console.log("app.js => onMessageReceivedCallback - " + JSON.stringify(message));
}
}).then(
function (instance) {
console.log("app.js => firebase.init done, instance = " + instance);
firebase.subscribeToTopic("all").then(
() => {console.log("app.js => subscribeToTopic(all): OK => subscribed");},
(error) => {console.log("app.js => subscribeToTopic(all): ERROR => " + error);}
);
},
function (error) {
console.log("app.js => firebase.init error: " + error);
}
);
Thank you @pjuros. I love you.
To avoid error in .then()
5.5.0 - [Firebase/Messaging][I-FCM002010] The subscription operation is suspended because you don't have a token. The operation will resume once you get an FCM token.
You can subscribe to topic after you receive your token like this:
firebase.init({
onPushTokenReceivedCallback: function(token) {
console.log("Firebase push token: " + token);
firebase.subscribeToTopic("all");
}
})
Most helpful comment
For me, file was firebase.nativescript.json located at the root folder of project and editing it didn't work.
How I fixed it:
You can check if firebase instance exists with: