如何在每次组件或页面访问时刷新工具栏(每次使用任何资源时)

How to refresh toolbar with every component or page visit (every time when any resource is used)

我编写了一个 Ionic 应用程序,它为每个页面显示一个工具栏。此工具栏包含一个徽章,向已登录用户显示未读消息(附截图)。工具栏组件在 ngOnInit 方法中从服务读取未读消息。

组件html文件:

<ion-header>
<ion-toolbar color="dark">
    <ion-title>
        <h5>{{title}}</h5>
    </ion-title>
    <ion-buttons slot="start">
        <ion-back-button defaultHref="profiles/guardian-profile"></ion-back-button>
    </ion-buttons>
    <ion-buttons slot="secondary">
        <ion-button>
            <ion-badge *ngIf="unreadNotifications" color="danger" [routerLink]="'/guardian-profile/guardian-notices'">{{unreadNotifications}}</ion-badge>
            <ion-badge *ngIf="!unreadNotifications"color="danger" [routerLink]="'/guardian-profile/guardian-notices'">{{announcementsNo}}</ion-badge>
        </ion-button>
        <ion-button (click)="logout()">
            <ion-icon slot="icon-only" name="exit"></ion-icon>
        </ion-button>
    </ion-buttons>
</ion-toolbar>

组件 ts 文件:

import {Component, Input, OnInit} from '@angular/core';
import {BaseHeaderClass} from '../../common/base-header-class';
import {EventService} from '../../services/event.service';
import {AuthService} from '../../services/auth.service';
import {Router} from '@angular/router';

@Component({
    selector: 'app-guardian-header',
    templateUrl: './guardian-header.component.html',
    styleUrls: ['./guardian-header.component.scss'],
})
export class GuardianHeaderComponent extends BaseHeaderClass implements OnInit {

    @Input() headerTitle: string;
    @Input() unreadNotifications: number;
    announcementsNo: number;

    constructor(private eventService: EventService, protected authService: AuthService, protected router: Router) {
        super(authService, router);
    }

    getData() {
        this.eventService.getActiveNoticesOfLoggedGuardian().subscribe(res => {
            this.announcementsNo = res.length;
        });
    }

    ngOnInit() {
        if (this.headerTitle) {
            this.title = this.headerTitle;
        } else {
            this.title = 'School Mate - Guardian View';
        }
        this.getData();
    }

    ionViewWillEnter() {
        this.getData();
    }
}

现在,当我阅读一条消息然后在我的组件和页面之间导航时,消息的数量正在更新,但仅限于我以前没有去过的地方。如果我在消息数量不变之前访问了特定的地方。 我每次去任何地方都需要更新这个,不管我是否去过那个地方。

我也不想用@Input() 变量将该数字发送到组件,我希望它像现在一样保持自我管理(我的组件仍然有这个注入,我想摆脱它)。我需要我的工具栏在必要时刷新未读消息。

您可以订阅导航路线的变化,因此每次用户导航到另一条路线时,该事件都应该发出一个新值。

constructor(private router: Router) {}

ngOnInit() {
        this.router.events.subscribe(event => {
            if (event instanceof NavigationEnd) {
                // your code goes here
            }
         });
}

希望对您有所帮助。祝你好运! :)