添加到数组的Angular 5元素以某种方式被删除

时间:2018-07-19 14:01:03

标签: angular

我有一个比赛管理器应用程序,当创建比赛时,它将添加到模拟数据数组中。它确实将其添加到数组中,但是当我尝试查看竞争时,它以某种方式被删除。

在组件中创建比赛的代码:

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]]}
];

1 个答案:

答案 0 :(得分:0)

如果您通过标准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;
  [...]
}