правки
This commit is contained in:
Kataev Denis 2022-09-16 10:41:32 +04:00
parent 4727a14ea0
commit 7b9a13231d
4 changed files with 108 additions and 30 deletions

View File

@ -28,7 +28,7 @@
"src/favicon.ico", "src/favicon.ico",
"src/assets", "src/assets",
"src/manifest.webmanifest", "src/manifest.webmanifest",
"src/assets/firebase-messaging-sw.js" "src/firebase-messaging-sw.js"
], ],
"styles": [ "styles": [
"node_modules/primeng/resources/themes/bootstrap4-light-blue/theme.css", "node_modules/primeng/resources/themes/bootstrap4-light-blue/theme.css",

View File

@ -31,6 +31,7 @@ import { RefSystemComponent } from './pages/account/ref-system/ref-system.compon
import { QRCodeModule } from 'angularx-qrcode'; import { QRCodeModule } from 'angularx-qrcode';
import { ShareButtonsModule } from 'ngx-sharebuttons/buttons'; import { ShareButtonsModule } from 'ngx-sharebuttons/buttons';
import { ShareIconsModule } from 'ngx-sharebuttons/icons'; import { ShareIconsModule } from 'ngx-sharebuttons/icons';
import { MessagingService } from './services/messaging.service';
@NgModule({ @NgModule({
declarations: [ declarations: [
@ -79,7 +80,7 @@ import { ShareIconsModule } from 'ngx-sharebuttons/icons';
}), }),
ShareIconsModule ShareIconsModule
], ],
providers: [DialogService, MessageService, ], providers: [DialogService, MessageService, MessagingService ],
bootstrap: [AppComponent] bootstrap: [AppComponent]
}) })
export class AppModule { } export class AppModule { }

View File

@ -4,6 +4,7 @@ import { ActivatedRoute } from "@angular/router";
import { CardComponent } from "src/app/components/card/card.component"; import { CardComponent } from "src/app/components/card/card.component";
import { AccountComponent } from "../account/account.component"; import { AccountComponent } from "../account/account.component";
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import { MessagingService } from "src/app/services/messaging.service";
@Component({ @Component({
@ -17,7 +18,8 @@ export class MainComponent implements OnInit {
public messagingToken!: string | null; public messagingToken!: string | null;
public deferredPrompt: any; public deferredPrompt: any;
public isPermissionNotifications: boolean = false; public isPermissionNotifications: boolean = false;
public token = '' public token = '';
public message: any;
constructor( constructor(
private route: ActivatedRoute, private route: ActivatedRoute,
@ -25,7 +27,8 @@ export class MainComponent implements OnInit {
private afMessaging: AngularFireMessaging, private afMessaging: AngularFireMessaging,
public el: ElementRef, public el: ElementRef,
public renderer: Renderer2, public renderer: Renderer2,
private messageService: MessageService private messageService: MessageService,
private messagingService: MessagingService
) { ) {
renderer.listen('window', 'appinstalled', (evt) => { renderer.listen('window', 'appinstalled', (evt) => {
console.log('INSTALLED!!!') console.log('INSTALLED!!!')
@ -61,34 +64,39 @@ export class MainComponent implements OnInit {
} }
requestPermission() { requestPermission() {
if (!('serviceWorker' in navigator)) { // if (!('serviceWorker' in navigator)) {
this.messageService.add({severity:'error', summary:'Не поддерживается в Вашем браузере!'}); // this.messageService.add({severity:'error', summary:'Не поддерживается в Вашем браузере!'});
return; // return;
} // }
if (!('PushManager' in window)) { // if (!('PushManager' in window)) {
// Браузер не поддерживает push-уведомления. // // Браузер не поддерживает push-уведомления.
this.messageService.add({severity:'error', summary:'Не поддерживается в Вашем браузере!'}); // this.messageService.add({severity:'error', summary:'Не поддерживается в Вашем браузере!'});
return; // return;
} // }
this.afMessaging.requestPermission.subscribe({ // this.afMessaging.requestPermission.subscribe({
next: () => { // next: () => {
console.log('Permission granted! Save to the server!') // console.log('Permission granted! Save to the server!')
}, // },
error: e => console.error(e) // error: e => console.error(e)
}) // })
this.afMessaging.requestToken.subscribe({ // this.afMessaging.requestToken.subscribe({
next: (token) => { // next: (token) => {
this.messagingToken = token; // this.messagingToken = token;
if (this.messagingToken) { // if (this.messagingToken) {
this.messageService.add({severity:'success', summary:'Спасибо за подписку!'}); // this.messageService.add({severity:'success', summary:'Спасибо за подписку!'});
this.isPermissionNotifications = true; // this.isPermissionNotifications = true;
} // }
console.log(token) // console.log(token)
}, // },
error: e => console.error(e) // error: e => console.error(e)
}) // })
const userId = 'user001';
this.messagingService.requestPermission(userId)
this.messagingService.receiveMessage()
this.message = this.messagingService.currentMessage
} }
// test function // test function

View File

@ -0,0 +1,69 @@
import { Injectable } from '@angular/core';
// import { AngularFireDatabase } from '@angular/fire/database';
// import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFireMessaging } from '@angular/fire/compat/messaging';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class MessagingService {
currentMessage = new BehaviorSubject(null);
constructor(
// private angularFireDB: AngularFireDatabase,
// private angularFireAuth: AngularFireAuth,
private angularFireMessaging: AngularFireMessaging
) {
this.angularFireMessaging.messages.subscribe((_messaging: any) => {
_messaging.onMessage = _messaging.onMessage.bind(_messaging);
_messaging.onTokenRefresh = _messaging.onTokenRefresh.bind(_messaging);
});
}
/**
* update token in firebase database
*
* @param userId userId as a key
* @param token token as a value
*/
// ОБНОВИТЬ/ДОБАВИТЬ ТОКЕН В БД
// updateToken(userId, token) {
// // we can change this function to request our backend service
// this.angularFireAuth.authState.pipe(take(1)).subscribe(
// () => {
// const data = {};
// data[userId] = token
// this.angularFireDB.object('fcmTokens/').update(data)
// })
// }
/**
* request permission for notification from firebase cloud messaging
*
* @param userId userId
*/
requestPermission(userId: string) {
this.angularFireMessaging.requestToken.subscribe({
next: (token) => {
// this.messagingToken = token;
// if (this.messagingToken) {
// this.messageService.add({severity:'success', summary:'Спасибо за подписку!'});
// this.isPermissionNotifications = true;
// }
console.log(token);
},
error: (e) => console.error(e),
});
}
/**
* hook method when new notification received in foreground
*/
receiveMessage() {
this.angularFireMessaging.messages.subscribe((payload: any) => {
console.log('new message received. ', payload);
this.currentMessage.next(payload);
});
}
}