具有 Ionic 3 延迟加载的本机存储模块

Native Storage module with Ionic 3 Lazy loading

我的 Ionic 3 应用程序有大约 10 页,我已经实现了延迟加载 feature.Now 我有一个关于 Native Storage module 的问题。我需要将它导入到 [=11= 中吗? ] 文件或者如果我将它导入每个页面的模块是否可以?推荐的使用方式是什么,当然还有最佳做法?

app.module.ts

@NgModule({
  declarations: [
    MyApp,
  ],
  imports: [
      IonicStorageModule.forRoot(),
  ],

正如您在 the docs 中看到的那样,建议使用存储的方式是将其添加到 AppModule:

Next, add it to the imports list in your NgModule declaration (for example, in src/app/app.module.ts):

import { IonicStorageModule } from '@ionic/storage';

@NgModule({
  declarations: [
    // ...
  ],
  imports: [      
    BrowserModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    // ...
  ],
  providers: [
    // ...
  ]
})
export class AppModule {}

然后

Finally, inject it into any of your components or pages:

import { Storage } from '@ionic/storage';

export class MyApp {
  constructor(private storage: Storage) { }

  ...

  // set a key/value
  storage.set('name', 'Max');

  // Or to get a key/value pair
  storage.get('age').then((val) => {
    console.log('Your age is', val);
  });
}

如果您不想这样做,而是希望将其添加到每个页面的模块中,则每个模块都会使用一个新的存储实例,但由于数据存储在同一位置整个应用程序,我想结果看起来是一样的,但我建议将它从 app.component.ts 添加到 AppModule,以便 在整个应用程序中使用相同的实例应用.


更新

就像你在Angular docs中看到的那样:

Why is a service provided in a lazy-loaded module visible only to that module?

Unlike providers of the modules loaded at launch, providers of lazy-loaded modules are module-scoped.

When the Angular router lazy-loads a module, it creates a new execution context. That context has its own injector, which is a direct child of the application injector.

The router adds the lazy module's providers and the providers of its imported modules to this child injector.

These providers are insulated from changes to application providers with the same lookup token. When the router creates a component within the lazy-loaded context, Angular prefers service instances created from these providers to the service instances of the application root injector.

这在使用 Storage 时可能不太容易看到,因为数据存储在同一个地方(下面的存储引擎),但假设我们想要注入一个 StatusProvider 其中包含一个 public status: boolean 属性。

因为您使用的是延迟加载模块(并且每个模块都有自己的执行上下文) 如果您在 [=19= 中包含 StatusProvider ] 数组 AppModule (在 app.module.ts 文件中),StatusProvider 的相同实例将在整个应用程序中使用。因此,如果您在应用程序的某处更改 status 属性,然后来自不同模块的另一个组件尝试读取该值,它将看到更新后的值,因为同一个实例在整个应用程序中共享应用

相反,如果您在每个子模块的 providers 数组中添加 StatusProvider,同样,由于每个子模块都有自己的执行上下文,因此每个子模块都会有自己的 StatusProvider。因此,如果您尝试修改一个子模块内的 status 属性,该更改将不会在其他(延迟加载的)子模块中看到。