【问题标题】:Angular2 component not updating based on changes to databaseAngular2 组件不会根据对数据库的更改进行更新
【发布时间】:2016-10-17 22:41:27
【问题描述】:

我是 Angular 的新手,我正在尝试使用我已经创建的 API 对我在表格中显示的一些数据执行基本的 CRUD 操作。这些操作似乎工作正常(我在 AWS 中的数据库正在更新),但我的视图没有更新。例如,如果我删除了一个播放器,它确实会从我的数据库中删除,但组件视图(显示在我的页面上的表格)不会刷新,因此仍会显示已删除的播放器。

我知道我应该使用 Observable 来保持一切同步,但我认为我没有正确实现它。谁能告诉我我做错了什么?

scores-table.component.ts

import { Component } from '@angular/core';
import { HighScore } from './high-score';
import { ScoreDataService } from './score-data.service';

@Component({
  selector: 'scores-table',
  templateUrl: 'app/scores-table.component.html'
})

export class ScoresTableComponent {
    errorMessage: string;
    statusCode: string;
    highScores: HighScore[];
    mode = 'Observable';

    constructor(private scoreDataService: ScoreDataService) {}

    ngOnInit() {
      this.getScores();
    }

    getScores() {
      return this.scoreDataService.getScores().subscribe(
                       highScores => this.highScores = highScores,
                       error =>  this.errorMessage = <any>error);
    }

    addPlayer (email: string, score: number) {
      this.errorMessage = "";
      if (!email || !score) { return; }
      this.scoreDataService.addPlayer(email, score)
                       .subscribe(
                         code => this.statusCode = code,
                         error =>  this.errorMessage = <any>error);
    }

    deletePlayer(email: string) {
      this.scoreDataService.deletePlayer(email);
    }
}

score-data.service.ts

import {Injectable} from '@angular/core';
import { Observable } from 'rxjs/Rx';
import {Http, Response} from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import {HighScore} from '../app/high-score'

@Injectable()
export class ScoreDataService {
  private url = "MY API URL";

  constructor(private http:Http){ }

  getScores(): Observable<HighScore[]> {
    return this.http.get(this.url)
      .map(this.extractData)
      .catch(this.handleError);
  }

  addPlayer(email: string, score: number): Observable<string> {
    let body = JSON.stringify({ email, score });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.url, body, options)
                    .map(this.extractStatus)
                    .catch(this.handleError);
  }

  deletePlayer(email: string) {
    return this.http.delete(this.url + email).subscribe();
  }

  private extractData(res: Response) {
    let body = res.json();
    return body.message || { };
  }

  private extractStatus(res: Response) {
    let status = res.json();
    return status.statusCode || { };
  }

  private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
  }
}

scores-table.component.html

<table>
    <tr *ngFor="let highScore of highScores">
        <td>{{highScore.email}}</td>
        <td>{{highScore.score}}</td>
        <td><button (click)="deletePlayer(highScore.email)"> X </button></td>
    </tr>
</table>

<h2>Add New Player</h2>
Player email:<br>
<input #email />
<br>
High Score:<br>
<input #score />
<br><br>
<button (click)="addPlayer(email.value, score.value)">Add Player</button>
<div class="error" *ngIf="errorMessage">{{errorMessage}}</div>

【问题讨论】:

    标签: angular


    【解决方案1】:

    应用程序:

    deletePlayer(email: string) {
       this.scoreDataService.deletePlayer(email)
         .subscribe(
            this.highScores = this.highScores.filter(highScore => highScore.email !== email);
          );
    }
    

    服务:

    deletePlayer(email: string) {
      return this.http.delete(this.url + email);
    }
    

    【讨论】:

    • 非常感谢!对于处于相同情况的其他人,我不得不稍微更改上面的代码以使其工作:
    • this.highScores = this.highScores.filter(highScore => highScore.email !== email)
    • 顺便问一下,你知道我会如何为 addPlayer 做这个吗?我尝试实施与 deletePlayer 相同的策略,但没有成功。
    • 我用 highScore 作为参数更新了我的答案。你有没有把服务中的人返回并推送到订阅中的数组中?另外...catch 方法在您的服务中做了什么?我不确定,但我认为您混淆了 Promises 和 Observables 的 catch 方法......
    • 只需删除“catch”,返回人员并将其推送到数组并告诉我它是否正常工作:)
    猜你喜欢
    • 2019-06-24
    • 2021-03-03
    • 2022-01-13
    • 2012-03-30
    • 2017-08-02
    • 2017-08-24
    • 2017-02-12
    • 2023-04-03
    • 2016-12-18
    相关资源
    最近更新 更多