Angular * ngЕсли обновление после нажатия на странице или на вкладке alt + (перефокусировка) - PullRequest
0 голосов
/ 05 марта 2020

У меня странная ошибка в проекте angular, это фрагменты кода

@Injectable()
export class FirebaseMessagingService {
    public tokenReceivedEmitter: any = new EventEmitter();
    public messageReceivedEmitter: any = new EventEmitter();

constructor(
    private angularFireMessaging: AngularFireMessaging) {
    this.angularFireMessaging.messaging.subscribe(
        (messaging) => {
            messaging.onMessage = messaging.onMessage.bind(messaging);
            messaging.onTokenRefresh = messaging.onTokenRefresh.bind(messaging);
        }
    );
}

/**
 * request permission for notification from firebase cloud messaging
 *
 * @param userId userId
 */
requestPermission(userId) {
    this.angularFireMessaging.requestToken.subscribe(
        (token) => {
            this.tokenReceivedEmitter.emit({status: true, result: token});
        },
        (err) => {
            this.tokenReceivedEmitter.emit({status: false, result: err});
        }
    );
}

/**
 * hook method when new notification received in foreground
 */
receiveMessage() {
    this.angularFireMessaging.messages.subscribe(
        (payload) => {
            this.messageReceivedEmitter.emit(payload);
        });
}

Так что это была служба обмена сообщениями Firebase, которая генерирует события получения токена и когда pu sh уведомление получено.

Теперь в компоненте

ngOnInit(){
    // Subscribing to firebase token receive
         this.firebaseTokenSubscription = this.messagingService.tokenReceivedEmitter.subscribe(
            (message) => {
                if (message.status) {
                    const token = message.result;
                    this.sendNotificationToken(token);
                } else {
                    this.snackBar.open(message.result, this.translate.instant('CLOSE') 
                    {duration:3000});
                }
        }
    );
}

А также у меня есть кнопка включения / выключения в компоненте, вот html части этого кода

<div *ngIf="user && !user.webPushEnabled"
     class="user-verification fx-all-100 layout-all-row-wrap">
    <div class="fx-gtSm-48 fx-ltMd-100 layout-all-col-nowrap">
        <p>{{"EXCHANGE.PROFILE.ENABLE_DISABLE_NOTIFICATION" | translate}}</p>
    </div>
    <div class="fx-gtSm-48 fx-ltMd-100 offset-gtSm-4 align-all-fxEnd-fxStr">
        <button mat-raised-button class="button-auth button-main-shadow"
                (click)="updateNotificationStatus(true)">
            {{"EXCHANGE.PROFILE.ENABLE_NOTIFICATIONS_BUTTON" | translate}}
        </button>
    </div>
</div>

<div *ngIf="user && user.webPushEnabled"
     class="user-verification fx-all-100 layout-all-row-wrap">
    <div class="fx-gtSm-48 fx-ltMd-100 layout-all-col-nowrap">
        <p>{{"EXCHANGE.PROFILE.ENABLE_DISABLE_NOTIFICATION" | translate}}</p>
    </div>
    <div class="fx-gtSm-48 fx-ltMd-100 offset-gtSm-4 align-all-fxEnd-fxStr">
        <button mat-raised-button class="del-api-key-btn button-main-shadow"
                (click)="updateNotificationStatus(false)">
            {{"EXCHANGE.PROFILE.DISABLE_NOTIFICATIONS_BUTTON" | translate}}
        </button>
    </div>
</div>

И, очевидно, у меня есть

 updateNotificationStatus(on: boolean) {
        if (on) {
            this.messagingService.requestPermission(this.user.userId);
        } else {
            this.userService.updateNotificationStatus(null, false).subscribe(
                (result) => {
                    this.user.webPushEnabled = false;
                },
                (error) => {
                    this.snackBar.open(error, this.translate.instant('CLOSE'), {duration: 3000});
                }
            );
        }
}

sendNotificationToken(token) {
    this.userService.updateNotificationStatus(token, true).subscribe(
        (result) => {
            debugger;
            this.user.webPushEnabled = true;
        },
        (error) => {
            this.snackBar.open(error, this.translate.instant('CLOSE'), {duration: 3000});
        }
    );
}

Проблема в том, что когда я включаю уведомления pu sh, он обновляется только html, когда страница перезагружается или перефокусируется (alt + tab или нажатие на страницу с помощью мышь). Он также отлично работает, когда веб-страница загружается в первый раз. Просьба помочь любые предложения или идеи могут помочь.

1 Ответ

0 голосов
/ 09 марта 2020

Проблема была в том, что firebase запрашивал токен пользователя вне потока просмотра Angular, поэтому мне пришлось обновить модель в потоке просмотра angular.

this.ngZone.run(() =>{
     this.user.webPushEnabled = true;
})

Это помогло мне .

...