我正在使用Angular2和MVC。我跟着很多關於angular.io的教程,但改變了一些東西來實現我自己的解決方案。基本上我有一個表格顯示客戶端及其標識符號碼。使用模擬數據,我能夠檢索客戶端並添加新的客戶端。新的將更新我的clientList並在我的顯示錶中顯示新的客戶端。Angular 2 Post更新我的列表,但不更改視圖
一旦我開始轉換這個命中服務器來獲取和發佈數據,我開始有問題。
我能夠從服務器上完美地檢索數據,它給了我期望的輸出。當我嘗試發佈一個新的服務器時,它進入我的post方法非常好。它將值推入我的clientList,但不更新我的顯示錶。
我想補充一點,我實際上並沒有將數據添加到服務器端的列表中,我只是簡單地返回一個新對象來試圖讓它更新我的視圖。
這裏是我的服務:
import {Injectable} from 'angular2/core';
import {Client} from './client';
import {RequestOptions, Http, Response, Headers} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class ClientService {
constructor(private http: Http) { }
getClients(): Observable<Client[]> {
return this.http.get('/Client/GetClients')
.map(this.extractData);
}
addClient(client: Client): Observable<Client> {
let clientUrl = '/Client/AddClient';
let body = JSON.stringify({ client });
let header = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: header });
return this.http.post(clientUrl, body, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
if (res.status < 200 || res.status >= 300) {
throw new Error('Bad response status: ' + res.status);
}
let body = res.json();
return body || {};
}
private handleError(error: any) {
// In a real world app, we might send the error to remote logging infrastructure
let errMsg = error.message || 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
我的應用程序組件:
@Component({
selector: 'my-app',
templateUrl: 'Scripts/typescript/app.component.html',
directives: [ClientFormComponent, MODAL_DIRECTIVES],
providers: [ClientService, HTTP_PROVIDERS]
})
@Injectable()
export class AppComponent implements OnInit {
constructor(private _clientService: ClientService) { }
currentClient: Client;
@ViewChild('modal')
modal: ModalComponent;
public clients: Client[];
public errorMessage: string;
ngOnInit() {
this.getClients();
}
getClients() {
this._clientService.getClients().subscribe(clients => this.clients = clients, error => this.errorMessage = <any>error);
}
deleteClient() {
var index = this.clients.indexOf(this.currentClient, 0);
if (index > -1) {
this.clients.splice(index, 1)
}
}
close() {
this.modal.close();
}
open(client: Client) {
this.currentClient = client;
this.modal.open();
我與調用服務組件,當我點擊添加按鈕:
@Component({
selector: 'client-form',
templateUrl: 'Scripts/typescript/client-form.component.html'
})
export class ClientFormComponent
{
constructor(private _clientService: ClientService) { }
@Input() clientList;
model = <Client>{ name: 'Bob', npi: 12345678 };
submitted = false;
active = true;
errorMessage: string;
onSubmit() { this.submitted = true; }
ngOnInit() {
this.getClients();
}
getClients() {
this._clientService.getClients()
.subscribe(
clients => this.clientList = clients,
error => this.errorMessage = <any>error);
}
addClient() {
this._clientService.addClient(this.model)
.subscribe(
client => this.clientList.push(client),
error => this.errorMessage = <any>error);
}
}
這裏是我顯示錶格的模板,它是app.component.html:
<h1>Client/NPI Cross Reference</h1>
<client-form></client-form>
<table class="table">
<tr style="font-weight: bold;">
<td>Client</td>
<td>NPI</td>
<td>Date Added</td>
<td></td>
</tr>
<tr *ngFor="#client of clients;">
<td>{{client.name}}</td>
<td>{{client.npi}}</td>
<td>{{client.dateAdded}}</td>
<td>
<span style="color: red; font-size: 16px; cursor: pointer;" class="glyphicon glyphicon-trash" aria-hidden="true" (click)="open(client)"></span>
</td>
</tr>
</table>
<modal #modal [animation]="animationsEnabled" (onClose)="deleteClient()" (onDismiss)="dismissed()">
<modal-header [show-close]="true">
<h4 class="modal-title">Delete</h4>
</modal-header>
<modal-body>
Are you sure you want to delete this entry?
</modal-body>
<modal-footer>
<button type="button" class="btn btn-primary" (click)="modal.close()">Yes</button>
<button type="button" class="btn btn-default" data-dismiss="modal" (click)="modal.dismiss()">No</button>
</modal-footer>
</modal>
這裏是我的表單模板的html:
<div class="container">
<form *ngIf="active" (ngSubmit)="onSubmit()" #clientForm="ngForm">
<div class="form-group" style="float: left;">
<label for="clientid">Client Id:</label>
<input type="text" class="form-control" required [(ngModel)]="model.name" ngControl="name" #name="ngForm" #newClient>
<div [hidden]="name.valid || name.pristine" class="alert alert-danger">
Name is required
</div>
</div>
<div class="form-group" style="float: left; padding-left: 10px;">
<label for="npi">NPI:</label>
<input type="number" class="form-control" required [(ngModel)]="model.npi" ngControl="npi" #newNpi>
</div>
<div style="float: left; margin: 25px 0 0 10px;">
<button type="submit" class="btn btn-default" (click)="addClient()" [disabled]="!clientForm.form.valid">Add</button>
</div>
</form>
</div>
<br style="clear:both;" />
在服務器端,我只是簡單地返回一個JSON客戶端:
[HttpPost]
public JsonResult AddClient()
{
var client = new Models.Client();
client.name = "test";
client.npi = 12345;
client.dateAdded = DateTime.Now.ToShortDateString();
return Json(client);
}
當使用模擬數據時,它會自動更新我的表格,我可以在表格中看到我的新客戶端。但現在我正在使用服務器,它將其添加到clientList,但它實際上並沒有改變我的表的視圖。
我如何獲得它來更改我的表格並更新它以顯示它已被添加?
您能否提供顯示錶格的方式?謝謝! –
爲兩個模板添加了html。 – Bohms27