【发布时间】: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