2016-04-26 96 views
0

我正在使用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,但它實際上並沒有改變我的表的視圖。

我如何獲得它來更改我的表格並更新它以顯示它已被添加?

+0

您能否提供顯示錶格的方式?謝謝! –

+0

爲兩個模板添加了html。 – Bohms27

回答

1

也許一點是,你在呼喚你ClientService的兩倍方法getClients(),從ClientFormComponent從該AppComponent各一次。

這意味着您將獲得2個不同的陣列,其中一個保存在AppComponent中,另一個保存在ClientFormComponent中。

如果我說的是正確的,那麼當你通過POST命令添加一個新客戶端時,然後ClientFormComponent更新它的數組,但是這對AppComponent數組(這是一個不同的對象)沒有影響。

在這種情況下的解決方案可能是:

1)使AppComponent通過其clients陣列到ClientFormComponent<client-form [clientList]="clients"></client-form>(這可能是)爲什麼clientList@Input()前面的原因

2)避免像地獄重置clientListClientFormComponent(這是目前發生在線this.clientList = clients

我希望我不會錯過克什麼,這可以幫助。

PS:我猜你不需要在AppComponent @Injectable(),因爲它是一個組件

+0

我改變了這一點,它現在可以工作,但它很奇怪,因爲這是工作正確的方式,我開始試圖做一個職位後,服務器。謝謝你的幫助! – Bohms27

1

這是我認爲正在發生的事情。當您在ClientFormComponent內調用getClients()時,它會用新陣列替換clientsList。但是,視圖中的那個是由getClients()AppComponent內分配的數組。以確保一種方式是評論裏面ClientFormComponent行:

ngOnInit() { 
    //this.getClients(); 
} 
+0

我評論了它,並仍然有同樣的問題。在我開始嘗試從服務器獲取數據並將數據發佈到服務器之前,它工作得很好,就像angular.io上的「Tour of Heroes」教程中使用「模擬客戶端」而不是他們使用的「模擬英雄」一樣。 – Bohms27

+0

我對Angular2仍然很陌生,但在它感覺像兩個組件中的「clients」和「clientList」被鏈接在一起之前。現在它感覺不連貫或什麼。 – Bohms27

+0

@ Bohms27在''將其更改爲'' – Abdulrahman

0

更改行:

公共機構提供服務:客戶端[];

公共客戶端:客戶端[] = [];