在Angular 6中,不再支持直接访问window.navigator.standalone
属性来检查Web应用是否在iOS的“Standalone”模式下运行。这是因为在Angular 6中,使用服务工作线程(Service Worker)来实现离线应用功能,而不是依赖于window.navigator.standalone
属性。
要检查应用是否在iOS的“Standalone”模式下运行,可以使用@angular/service-worker
库提供的SwUpdate
服务。以下是一个代码示例:
首先,安装@angular/service-worker
库:
npm install @angular/service-worker --save
然后,在app.module.ts
文件中导入ServiceWorkerModule
并添加到imports
数组中:
import { ServiceWorkerModule } from '@angular/service-worker';
@NgModule({
imports: [
ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production })
],
// ...
})
export class AppModule { }
接下来,在组件中使用SwUpdate
服务来检查是否在“Standalone”模式下运行:
import { Component } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';
@Component({
selector: 'app-root',
template: `
Angular 6 Standalone Mode
Running in "Standalone" mode
Not running in "Standalone" mode
`
})
export class AppComponent {
isStandalone: boolean;
constructor(private swUpdate: SwUpdate) {
this.isStandalone = window.matchMedia('(display-mode: standalone)').matches;
// 订阅更新通知以检查是否在“Standalone”模式下运行
this.swUpdate.available.subscribe(() => {
this.isStandalone = window.matchMedia('(display-mode: standalone)').matches;
});
}
}
在上面的代码中,我们通过使用window.matchMedia('(display-mode: standalone)').matches
来检查是否在“Standalone”模式下运行。然后,我们订阅SwUpdate
服务的available
事件来在应用程序有更新可用时重新检查是否在“Standalone”模式下运行。
这样,我们就可以在Angular 6中检查应用是否在iOS的“Standalone”模式下运行了。