FCMPlugin is not Defined in home.ts - firebase

I am trying to send a Push notification Using Firebase and Ionic 3. I have already imported the FCMPlugin in my project though my cmd. When I am creating a new message in firebase and try tos end, I don't receive anything, I run console log in my project and it gives me the following error "FCMPlugin is not defined".
I have declared the Plugin in my home.ts, but I am still getting this error, my home.ts is as follows:
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import {AlertController} from 'ionic-angular';
declare var FCMPlugin: any; // <---- this is the magic line
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(private alert:AlertController, private platform:Platform) {
this.onNotification();
}
async onNotification(){
try {
await this.platform.ready();
FCMPlugin.onNotification((data)=>{
this.alert.create({
message: data.message
}).present();
},(error) => console.error(error));
}
catch (e) {
console.error(e);
}
}
}
Can anyone provide me some guidance asIi am quite new to ionic?
Thanks in Regards

try using the FCM onNotification method inside an if block so that whenever you use it on a browser or whenever FCM is called before its initialisation it will not throw an error:
if (typeof FCMPlugin != 'undefined') {
FCMPlugin.onNotification((data)=>{})
}

Related

ionic 4 + firebaseX stopped receiving push (android and ios)

My app has stopped from receiving push notifications.
I don't know what else I can do to check it.
It was working a few months ago
Stopped working for both iOS and Android
Installed and checked app permissions many times
Firebase is initializing, getting token and registering in my database fine
Tried test messages on Firebase console with generated token and it didn't work as well
Here is my notification.service.ts code:
import { Injectable } from '#angular/core';
import { Platform, Events } from '#ionic/angular';
import { HttpClient } from '#angular/common/http';
import { Storage } from '#ionic/storage';
import { BehaviorSubject } from 'rxjs';
import { tap } from 'rxjs/operators';
import { FirebaseX } from "#ionic-native/firebase-x/ngx";
import { environment } from '../../environments/environment';
import { AppService } from './app.service';
import { AuthService } from './auth.service';
#Injectable({
providedIn: 'root'
})
export class NotificationService {
fcm_token:any = null;
constructor(
private platform: Platform,
private http:HttpClient,
private appService:AppService,
private firebase: FirebaseX,
public events: Events,
public authService:AuthService,
) { }
async initialize(){
console.log('notificationService.initialize()');
let self = this;
let platforms = this.platform.platforms();
if(platforms.includes('ios') || platforms.includes('android')){
this.firebase.getToken().then(token => {
if(platforms.includes('ios')){ this.firebase.grantPermission(); }
if(platforms.includes('android')){ }
self.saveToken(token);
}).catch(error => console.error('FIREBASE Error getting token', error));
this.firebase.onTokenRefresh().subscribe((token: string) => { self.saveToken(token); });
this.firebase.onMessageReceived().subscribe(data => { });
}else{
// using browser, do nothing
}
}
async saveToken(token){
console.log('notificationService.saveToken()', token);
if(this.authService.is_logged == true){
this.fcm_token = token;
return this.http.post(environment.api_url+'/user/save-fcm-token', {fcm_token:this.fcm_token}, {headers:{'Authorization':'Bearer '+this.authService.auth_token}}).toPromise();
}
}
}
What else can I try?
Is there some place when I can see sending/receiving push errors?

Handle 401 error in react-redux app using apisauce

The problem: i have many sagas that do not handle an 401 error in response status, and now i have to deal with it. I have apiservice based on apisause and i can write an response monitor with it to handle 401 error (like interceptors in axios). But i cant dispatch any action to store to reset user data, for example, because there is no store context in apiservice. How to use dispatch function in apiservice layer? Or use put() function in every saga when i recieve 401 response status is the only right way?
you can use refs for using navigation in 'apisauce' interceptors
this is my code and it works for me ;)
-- packages versions
#react-navigation/native: ^6.0.6
#react-navigation/native-stack: ^6.2.5
apisauce: ^2.1.1
react: 17.0.2
react-native: ^0.66.3
I have a main file for create apisauce
// file _api.js :
export const baseURL = 'APP_BASE_URL';
import { create } from 'apisauce'
import { setAPIInterceptors } from './interceptors';
const APIClient = create({ baseURL: baseURL })
setAPIInterceptors(APIClient)
and is file interceptors.js I'm watching on responses and manage them:
// file interceptors.js
import { logout } from "../redux/actions";
import { store } from '../redux/store';
import AsyncStorage from '#react-native-async-storage/async-storage';
export const setAPIInterceptors = (APIClient) => {
APIClient.addMonitor(monitor => {
// ...
// error Unauthorized
if(monitor.status === 401) {
store.dispatch(logout())
AsyncStorage.clear().then((res) => {
RootNavigation.navigate('login');
})
}
})
}
then I create another file and named to 'RootNavigation.js' and create a ref from react-native-navigation:
// file RootNavigation.js
import { createNavigationContainerRef } from '#react-navigation/native';
export const navigationRef = createNavigationContainerRef()
export function navigate(name, params) {
if (navigationRef.isReady()) {
navigationRef.replace(name, params);
}
}
// add other navigation functions that you need and export them
then you should to set some changes in you App.js file:
import { NavigationContainer } from '#react-navigation/native';
import { navigationRef } from './RootNavigation';
export default function App() {
return (
<NavigationContainer ref={navigationRef}>{/* ... */}</NavigationContainer>
);
}
finally in anywhere you can call this function for use react native navigations
full focument is in here that explain how to Navigating without the navigation prop
Navigating without the navigation prop

Quasar v2 Vue-Apollo Setup

I've recent switched over to Quasar v2 and I'm having trouble getting the info I need for the vue apollo setup. I am using https://apollo.vuejs.org/guide/installation.html#_1-apollo-client to try and install vue apollo into the framework using the boot file.
This is my boot/apollo.ts file
import { boot } from 'quasar/wrappers';
import ApolloClient from 'apollo-boost';
import VueApollo from 'vue-apollo';
const apollo = new ApolloClient({
uri: 'https://api.graphcms.com/simple/v1/awesomeTalksClone',
});
const apolloProvider = new VueApollo({
defaultClient: apollo,
});
export default boot(({ app }) => {
// for use inside Vue files (Options API) through this.$apollo
app.config.globalProperties.$apollo = apollo;
// ^ ^ ^ this will allow you to use this.$apollo (for Vue Options API form)
// so you won't necessarily have to import apollo in each vue file
});
export { apollo, VueApollo, apolloProvider };
And this is where I am trying to use it:
import { Vue } from 'vue-class-component';
export default class LoginPage extends Vue {
public login() {
console.log(this.$apollo);
}
}
The error I'm getting is
Property '$apollo' does not exist on type 'LoginPage'.
I can see in the comment for the globalProperties it mentions the vue options api. Not sure if this is happening because I use vue-class-component.
I ended up added this below the export
declare module '#vue/runtime-core' {
interface ComponentCustomProperties {
$apollo: FunctionConstructor;
}
}

from http to Http Client, cant get my object to become a string array [duplicate]

Following Google's official Angular 4.3.2 doc here, I was able to do a simple get request from a local json file. I wanted to practice hitting a real endpoint from JSON placeholder site, but I'm having trouble figuring out what to put in the .subscribe() operator. I made an IUser interface to capture the fields of the payload, but the line with .subscribe(data => {this.users = data}) throws the error Type 'Object' is not assignable to type 'IUser[]'. What's the proper way to handle this? Seems pretty basic but I'm a noob.
My code is below:
import { Component, OnInit } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { IUsers } from './users';
#Component({
selector: 'pm-http',
templateUrl: './http.component.html',
styleUrls: ['./http.component.css']
})
export class HttpComponent implements OnInit {
productUrl = 'https://jsonplaceholder.typicode.com/users';
users: IUsers[];
constructor(private _http: HttpClient) { }
ngOnInit(): void {
this._http.get(this.productUrl).subscribe(data => {this.users = data});
}
}
You actually have a few options here, but use generics to cast it to the type you're expecting.
// Notice the Generic of IUsers[] casting the Type for resulting "data"
this.http.get<IUsers[]>(this.productUrl).subscribe(data => ...
// or in the subscribe
.subscribe((data: IUsers[]) => ...
Also I'd recommend using async pipes in your template that auto subscribe / unsubscribe, especially if you don't need any fancy logic, and you're just mapping the value.
users: Observable<IUsers[]>; // different type now
this.users = this.http.get<IUsers[]>(this.productUrl);
// template:
*ngFor="let user of users | async"
I'm on the Angular doc team and one open todo item is to change these docs to show the "best practice" way to access Http ... which is through a service.
Here is an example:
import { Injectable } from '#angular/core';
import { HttpClient, HttpErrorResponse } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import { IProduct } from './product';
#Injectable()
export class ProductService {
private _productUrl = './api/products/products.json';
constructor(private _http: HttpClient) { }
getProducts(): Observable<IProduct[]> {
return this._http.get<IProduct[]>(this._productUrl)
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(err: HttpErrorResponse) {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
let errorMessage = '';
if (err.error instanceof Error) {
// A client-side or network error occurred. Handle it accordingly.
errorMessage = `An error occurred: ${err.error.message}`;
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
}
console.error(errorMessage);
return Observable.throw(errorMessage);
}
}
The component would then look like this:
ngOnInit(): void {
this._productService.getProducts()
.subscribe(products => this.products = products,
error => this.errorMessage = <any>error);
}

how to subscribe to firebase login events with angularfire2

I saw this example for how to subscribe to firebase auth events
this.firebase.onAuth((user) => {})
How can I do the same thing with angularfire2 and ionic2 and angular2 project?
constructor(nav:NavController, private auth: FirebaseAuth) {
auth.onAuth ... // I don't see any subscription events on the firbaseAuth object
}
I saw this syntax in the angularfire2 documentation but not sure what the | syntax means and how to do the same logic from the #Component declartion in the controller code:
import {FirebaseAuth} from 'angularfire2';
#Component({
selector: 'auth-status',
template: `
<div *ng-if="auth | async">You are logged in</div>
<div *ng-if="!(auth | async)">Please log in</div>
`
})
class App {
constructor (#Inject(FirebaseAuth) public auth: FirebaseAuth) {}
}
I don't know about Iconic, but using angularafire2 (2.0.0-beta.2). Here's how to do this. Assuming the project has been setup so that AngularFire is an injectable service. (I followed the instructions at Angularfire2 Github.)
#Component({
.. blah, blah, blah
})
export class MyComponent{
constructor(private AngularFire af){
af.subscribe.auth(auth => {
//the auth object contains the logged in user info
// if one exists.
console.log(auth)
});
}
In order to refer to the auth object from the html template (as in your example), just store the auth object returned by the call to subscribe as member variable. Your template code is just checking non-null to determine that there is a logged in user.
This has been updated in "angularfire2": "^4.0.0-rc.1"
The subscribe is now in authState from the import { AngularFireAuth } from 'angularfire2/auth';
So in your ngModule you need to add
import { AngularFireAuthModule } from 'angularfire2/auth';
And add it to your imports and then in your app.components.ts
this.af.authState.subscribe(auth => {
console.log(auth);
});

Resources