小编Pat*_*ung的帖子

即使@Injectable已providIn:'root',服务也会创建另一个实例。我如何确保服务是单例的?

我有 2 个服务位于 /services、AccountService 和 AuthenticationService。我还有 2 个页面:accounts.page 和 add-accounts.page 位于 /accounts 中,add-accounts.page 位于 /accounts/add-accounts 中。\n我在accounts.page 和 add- 中都使用 AccountService account.page 从本地 json 加载帐户并将其存储在 Ionic/Storage 中。因此计划是使用该服务从存储中获取帐户并添加新帐户。我在服务中有一个 ReplaySubject 来检测新的更改,我想在帐户 html 页面中使用它来显示帐户数组。\n我正在使用 Ionic 4 和 Angular 版本 7

\n

经过一番修改后,我发现该服务获得了 2 个实例,因此我没有向最初开始使用的 ReplaySubject 添加新的更改。我通过将 console.log 添加到服务的构造函数中发现了这一点,并在控制台中查看,从帐户页面转到添加帐户页面后,我发现了同一 console.log 的 2 个实例。因此,我在添加帐户页面中对 accountService 所做的更改是另一个实例,并且在第一个实例中没有更改。

\n

当我使用其他服务(AuthenticationService)对此进行测试时,我在控制台中没有得到 2 个 console.log 输出。 \n我仔细检查了 @Injectable 装饰器,如果它们具有 \xc2\xa0providedIn 的正确语法:'root'\xc2\ xa0 并在测试删除 \xc2\xa0providedIn: 'root'\xc2\xa0part 的旧角度方法并将服务导入 \xc2\xa0app.module.ts\xc2\xa0 并将其添加到 \xc2\xa0providers\xc2\ xa0array 我收到 a\xc2\xa0NullInjectorError: Noprovider for AccoutService\xc2\xa0Error 我无法解决。

\n

我尝试创建一个新服务并ionic g …

ionic-framework angular ionic4

4
推荐指数
1
解决办法
1872
查看次数

标签 统计

angular ×1

ionic-framework ×1

ionic4 ×1