Angular:通过依赖注入实现的Singleton Service问题

时间:2019-05-21 00:13:53

标签: angular dependency-injection

我已经实现了Singleton Service(即ApiService),并且我正在ProductCatalog模块中使用此Singleton Service,其中我们在Singleton Service中有两种方法getData()addData(),它们列出了数据并将数据添加到 ApiService 服务的私有数据数组中。

我们有两个部分:产品列表和产品更新。我们使用此组件从ApiService的私有Data变量中列出数据。

期望是当我们使用addData()单例服务方法时,应将新数据添加到Data数组,并导航到/ update时应列出产品更新组件上Data变量中的数据以及新添加的数据。

当前,只要我们通过addData()单服务方法将newData添加到数据数组中,就不会发生这种情况。我们只获得数据数组的初始状态,而没有反映新添加的数据。

因此,似乎我缺少一些步骤或实现。请帮助解决此问题。

这里是对代码的引用。 https://stackblitz.com/edit/angular-2uyx3a

2 个答案:

答案 0 :(得分:1)

核心模块中不需要forRoot。您已经以root用户身份提供了服务:

@Injectable(
  providedIn: 'root'
)

这意味着该服务在应用程序的根注入器中可用。 在这种情况下,核心模块是无用的。

Here is your stackblitz code working

我建议您查看Angular的文档以获取更多信息:

Hierarchical Dependency injection

Singleton Services

要注意的一件事:如果刷新浏览器或从浏览器地址栏中更改路由,状态将丢失。

答案 1 :(得分:1)

好吧,我认为您正在通过更改浏览器中的url进行导航,因为在提供的示例中没有提供导航的方法,这肯定无法正常工作,因为当您更改url时,您实际上是在重新加载应用程序,这会删除所有您的应用程序内存中的数据。

您的服务运行良好,您只需要使用@ angular / router进行导航,没有它无法处理手动的网址更改,并且没有其他可以做到的。

但是它将在该here - router official docs上通过Zuhoerer更多地处理链接

product-listing.component.html

内部
routerLink

它还可以使用 product-listing works! <p *ngFor="let item of sampleData">{{ item.id }} -{{ item.name }}</p> <!-- Example of using routerLink --> <a routerLink="/update">go to update</a> Router这样的功能通过navigateTo服务处理动态路由:

product-update.component.ts

内部
navigateByUrl

但是,要使这些路由方法中的任何一种起作用,您都需要向模块的导入(包括这些组件声明)中添加 // product-update.component.ts import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router' import { FormGroup, FormControl, FormArray } from '@angular/forms'; import { ApiService } from '../../core/api.service'; @Component({ selector: 'app-product-update', templateUrl: './product-update.component.html', styleUrls: ['./product-update.component.css'] }) export class ProductUpdateComponent implements OnInit { dataForm: FormGroup; // do not forget to import the service constructor(private api: ApiService, private router: Router) {} ngOnInit() { this.dataForm = new FormGroup({ id: new FormControl(' '), name: new FormControl(' ') }); } saveData() { this.api.addData({ id: this.dataForm.controls.id.value, name: this.dataForm.controls.name.value }); // Use of router service `navigateByUrl` to dynamically redirect to another view this.router.navigateByUrl('/listing') } } 。像这样:

product-catalog.module.ts

内部
RouterModule.forChild()

如果您这样做并按原样测试服务,就会发现它运行正常。

但是,再次在浏览器中手动更改url时,您正在重新加载应用程序,这会删除所有应用程序内存/数据,除非保存在后端。

这是指向编辑项目https://stackblitz.com/edit/angular-z2m9ri

的链接

希望这很有帮助