我已经实现了单例服务(即 ApiService),我在 ProductCatalog 模块中使用了这个单例服务,其中我们在单例服务中有两个方法,getData()
和addData()
,它们列出数据并将数据添加到ApiService服务中的私有数据数组中。
我们有两个组件产品列表和产品更新。我们使用这个组件来列出来自 ApiService 的私有 Data 变量中的数据。
期望是当我们使用addData()
单例服务的方法时,它应该将新数据添加到 Data 数组,并且在导航到 /update 时应该列出产品更新组件上 Data 变量中的数据以及新添加的数据。
目前,每当我们通过addData()
单一服务的方法将 newData 添加到数据数组时,这不会发生。我们只得到数据数组的初始状态,而没有反映新添加的数据。
因此,看起来我缺少一些步骤或实现。请帮助解决这个问题。
好的,我认为您是通过更改浏览器中的 url 进行导航的,因为在提供的示例中没有提供导航方式,这肯定不会像更改 url 时实际重新加载应用程序那样起作用,这会删除您的应用程序中的所有数据应用程序内存。
您的服务运行良好,您只需要使用 @angular/router 进行导航,并且它无法处理手动 url 更改,也没有其他任何方法可以做到这一点。
但它会通过routerLink
更多的链接来处理这里的链接- 路由器官方文档
在product-listing.component.html里面
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
service usingnavigateTo
或如下navigateByUrl
函数处理动态路由:
在product-update.component.ts里面
// 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')
}
}
但是要使这些路由方法中的任何一种工作,您都需要添加RouterModule.forChild()
到模块的导入中,包括这些组件声明。像这样:
在product-catalog.module.ts里面
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';
import {CoreModule } from '../core/core.module';
import { RouterModule } from '@angular/router';
import { ProductListingComponent } from './product-listing/product-listing.component';
import { ProductUpdateComponent } from './product-update/product-update.component';
@NgModule({
imports: [
CommonModule, ReactiveFormsModule,
CoreModule.forRoot(),
RouterModule.forChild([]) // Add this to the imports
],
declarations: [ProductListingComponent, ProductUpdateComponent]
})
export class ProductCatalogModule { }
如果您使用它并按原样测试您的服务,您会发现它运行良好。
但是,当您手动更改浏览器中的 url 时,您正在重新加载您的应用程序,这将删除所有应用程序内存/数据,除非保存在后端。
这是编辑项目的链接https://stackblitz.com/edit/angular-z2m9ri
希望这有帮助
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句