2016-04-26 157 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

更改行:

公共机构提供服务:客户端[];

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

相关问题