首页 > 解决方案 > 添加到数组的 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]]}
];

标签: angular

解决方案


如果您通过标准获取模拟数据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;
  [...]
}

推荐阅读