Angular 4 - 删除后的更新列表

时间:2018-01-06 16:55:57

标签: ruby-on-rails angular crud

我正在为即将举行的音乐会活动建立一个网站。当我创建一个新事件时,我将其保存到后端(Ruby on Rails)并立即在事件列表中显示新事件。但是,当我删除事件时,事件会在数据库中被删除,但前端不会刷新。

事件create.component.ts

import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators, FormBuilder } from "@angular/forms";
import { EventService } from "../event.service";
import { Event } from "../event";
import { Venue } from "../../venue/venue";
import { VenueService } from "../../venue/venue.service";
import { ActivatedRoute, Router} from '@angular/router';
import { BsDatepickerConfig } from 'ngx-bootstrap/datepicker'
import { DataService } from '../../data.service';

@Component({
  selector: 'app-event-create',
  templateUrl: './event-create.component.html',
  styleUrls: ['./event-create.component.scss']
})
export class EventCreateComponent implements OnInit {

  id: number;
  event: Event;
  venues: Venue[];

  bsValue: Date = new Date();
  date: string;
  time: string;
  datepickerModel: Date = new Date();
  bsConfig: Partial<BsDatepickerConfig>;
  eventTime: Date = new Date(this.bsValue.getFullYear(), this.bsValue.getMonth(), this.bsValue.getDay(), 19, 0, 0, 0);

  mstep: number = 15;

  eventForm: FormGroup;

  constructor(private route: ActivatedRoute,
              private router: Router,
              private eventService: EventService,
              private venueService: VenueService,
              private data: DataService,
              fb: FormBuilder) {
    this.eventForm = fb.group({
      'title': [null, Validators.required],
      'venue': [1, Validators.required],
      'date': null,
      'time': null,
      'description': [null, Validators.required]
      });
    this.bsConfig = Object.assign({}, { containerClass: 'theme-red' });
  }

  ngOnInit(): void {
    this.getVenues();
  }

  getVenues(){
    this.venueService.query().subscribe(
      venues => {
        this.venues = venues;
      },
      err => {
        console.log(err);
      }
    );
  }

  onSubmit() {
    Object.keys(this.eventForm.controls).forEach(field => {
      const control = this.eventForm.get(field);
      control.markAsTouched({ onlySelf: true });
    });
    if (this.eventForm.valid) {
      let date: Date = new Date(this.eventForm.controls['date'].value);
      let time: Date = new Date(this.eventForm.controls['time'].value);

      let event: Event = new Event(
        null,
        this.eventForm.controls['venue'].value,
        this.formatTimestamp(date, time),
        this.eventForm.controls['title'].value,
        this.eventForm.controls['description'].value
      );

      this.eventService.save(event).subscribe();

      this.data.addEvent(event);

      this.router.navigate(['/event']);
     }
  }

  formatTimestamp(date: Date, time: Date): number {
    let timezoneOffset: number = time.getTimezoneOffset() / 60;

    if((time.getHours() + timezoneOffset) > 23){
      date.setDate(date.getDate() + 1);
    }

    date.setUTCHours(time.getUTCHours());
    date.setUTCMinutes(time.getMinutes());
    date.setUTCSeconds(time.getSeconds());

    return date.getTime();
  }

  redirectUserPage() {
    this.router.navigate(['/user']);

  }
}

事件index.component.ts

import { Component, OnInit } from '@angular/core';
import { Event } from '../event';
import { EventService } from '../event.service';
import { Router } from '@angular/router';
import { DataService } from '../../data.service';
import { Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-event-index',
  templateUrl: './event-index.component.html',
  styleUrls: ['./event-index.component.scss']
})
export class EventIndexComponent implements OnInit {
  @Output()
  someEvent = new EventEmitter();

  event: Event;

  private events: Event[];

  constructor(
    private router: Router,
    private eventService: EventService,
    private data: DataService
  ) { }

  ngOnInit() {
    this.getEvents();
    this.data.currentEvent.subscribe(event => this.event = event);
  }

  getEvents(){
    this.eventService.query().subscribe(
      events => {
        this.events = events;
      },
      err => {
        console.log(err);
      }
    )
  }

  newEvent(){
    this.router.navigate(['/event/create']);
  }

  editEvent(event: Event){
    if(event){
      this.router.navigate(['/event/edit', event]);
    }
  }

  deleteEvent(event: Event){
    let index = this.events.indexOf(event);

    if(index > -1){
      this.eventService.delete(event).subscribe(
        event => {
          this.events.slice(index, 1);
        }
      );
    }
  }
}

data.service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Event } from './event/event';

@Injectable()
export class DataService{
  currentEvent: BehaviorSubject<Event> = new BehaviorSubject<Event>(null);

  public addEvent(newEvent: Event): void{
    this.currentEvent.next(newEvent);
  }
}

事件create.component.html

<div class="row justify-content-center">
  <h1>New Event</h1>
</div>

<div class='row justify-content-center'>
  <div class='col-6'>
    <form [formGroup]='eventForm' (ngSubmit)="onSubmit(eventForm.value)">
      <div class='form-group'>
        <label>Title</label>
        <input type="text" class='form-control' [ngClass]="{'is-invalid': eventForm.controls['title'].invalid && eventForm.controls['title'].touched}" formControlName="title">
        <div *ngIf="eventForm.controls['title'].hasError('required')" class="invalid-feedback">Title is required</div>
      </div>
      <div class='form-group'>
        <label>Description</label>
        <textarea formControlName="description" class='form-control' [ngClass]="{'is-invalid': eventForm.controls['description'].invalid && eventForm.controls['description'].touched}"></textarea>
        <div *ngIf="eventForm.controls['description'].hasError('required')" class="invalid-feedback">Description is required</div>
      </div>
      <div class='form-group'>
        <label>Venue</label>
        <select class='form-control' formControlName='venue'>
          <option *ngFor="let venue of venues" [value]="venue.id">{{venue.name}}</option>
        </select>
      </div>
      <div class="form-group">
        <label>Date</label>
        <input type="text" class="form-control" bsDatepicker [bsConfig]="bsConfig" [(ngModel)]="datepickerModel" formControlName='date'>
      </div>
      <div class='form-group'>
        <label>Time</label>
        <timepicker [(ngModel)]="eventTime" [minuteStep]="mstep" formControlName='time'></timepicker>
      </div>
      <button type="submit" class='btn btn-default'>Submit</button>
      <pre>{{eventForm.value | json}}</pre>
    </form>
  </div>
</div>

event.service.ts

import { Injectable } from '@angular/core';
import { Event } from './event';
import { HttpClient } from '@angular/common/http';
import { Response } from '@angular/http';
import { Observable } from 'rxjs/Observable'

@Injectable()
export class EventService {

  private apiUrl = 'http://localhost:3000/events';

  constructor(private http: HttpClient) {}

  query(): Observable<any>{
    return this.http.get(this.apiUrl);
  }

  get(id: number): Observable<Event>{
    return null;
  }

  save(event: Event): Observable<any>{
    return this.http.post(this.apiUrl, event);
  }

  delete(event: Event): Observable<any>{
    console.log(event);

    return this.http.delete(this.apiUrl + '/' + event.id)
  }

  update(event: Event): Observable<Event>{
    return null;
  }
}

1 个答案:

答案 0 :(得分:2)

您正在slice()使用splice() deleteEvent()

尝试更改:

this.events.slice(index, 1);

this.events.splice(index, 1);