angular - 添加到数组的 Angular 5 元素以某种方式被删除
问题描述
我有一个竞赛管理器应用程序,当创建竞赛时,它被添加到模拟数据数组中。它确实将它添加到数组中,但是当我尝试查看比赛时,不知何故被删除了。
在组件中创建比赛的代码:
const competition = new Competition();
competition.id = COMPETITIONS.length;
competition.name = this.competition_name;
competition.users = this.userArr;
this.competitionService.createCompetition(competition).subscribe(data => {
this.router.navigate(['/competition/index']);
});
服务中的代码以获得和创造竞争:
getCompetition(id: number): Observable<Competition> {
return of(COMPETITIONS.find(competition => Number(competition.id) === Number(id)));
}
createCompetition(competition): Observable<number> {
return of(COMPETITIONS.push(competition));
}
查看特定比赛的代码:
this.competitionService.getCompetition(route.snapshot.params.id).subscribe(data => {
if (data) {
this.competition = data;
} else {
router.navigate(['/competition/index']);
}
});
比赛模拟数据:
import {Competition} from '../classes/competition';
import {USERS} from './mock-users';
export const COMPETITIONS: Competition[] = [
{id: 0, name: 'Testje Compie', users: [USERS[0], USERS[3]]}
];
解决方案
如果您通过标准获取模拟数据import
,那可能是您问题的根源。为了确保数据在您浏览应用程序时保持不变,您应该将集合存储在服务本身中。
import { Injectable } from '@angular/core';
import { Competition } from '../classes/competition';
import { USERS } from './mock-users';
@Injectable({
providedIn: 'root',
})
export class CompetitionsService {
public COMPETITIONS: Competition[] = [
{id: 0, name: 'Testje Compie', users: [USERS[0], USERS[3]]}
];
constructor() { }
getCompetition(id: number): Observable<Competition> {
return of(this.COMPETITIONS.find(competition => Number(competition.id) === Number(id)));
}
createCompetition(competition): Observable<number> {
return of(this.COMPETITIONS.push(competition));
}
}
如果您真的想将模拟数据声明保留在单独的文件中,那么您可以更改服务以使用它
import { COMPETITIONS } from "competition.mockdata"
export class CompetitionsService {
public COMPETITIONS = COMPETITIONS;
[...]
}
推荐阅读
- reactjs - React - 更改子组件状态值
- python - Python函数的Dask Apply
- ruby-on-rails - 在 each_with_index 中显示每个项目的 Alpha 字符
- c++ - C++ libtins“指定了一个无效的句柄”
- php - 如何用php删除表中的特定行
- javascript - 如何为除社交链接之外的外部链接重定向页面
- javascript - 在导航菜单下拉菜单中添加阅读更多箭头
- python - 从 XML 文件中提取文本
- c# - 不能对调用静态方法的方法进行单元测试,我该如何重新设计这个程序?
- python - 在跟踪中设置悬停信息时,Python Plotly xaxis悬停文本消失