Angular2打字稿可观察到的问题

Angular2打字稿可观察到的问题

问题描述:

我采用了棱角分明2.0.0 beta.0和打字稿1.7.5Angular2打字稿可观察到的问题

在方法的类Test需要从Observable<Resource[]>this.resources类型提取并分配到与resourceId资源的saveResourcethis.resourceToSave类型Resource。通过这种方式,可以使用以下代码将已更改的资源存储在数据库中:this.resourceService.updateResource(this.resourceToSave).subscribe()

什么是正确的代码?

import {bootstrap}   from 'angular2/platform/browser'; 
import {Component}   from 'angular2/core'; 
import {HTTP_PROVIDERS} from 'angular2/http'; 
import {Observable}  from 'rxjs/Observable'; 
import {Subject}   from 'rxjs/Subject'; 
import 'rxjs/Rx'; 

import {Resource} from './classes/resource'; 
import {ResourceService} from "./services/resource-service"; 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div class="container"> 
     <div> 
      <h3>Resources Maintenance</h3> 
      <div class="form-group"> 
       <label for="inputUser">Search</label> 
       <input #inputUser (keyup)="search(inputUser.value)" autofocus> 
      </div> 
      <table style="width:65%" class="table-striped"> 
      <thead> 
      <tr> 
       <th>Resource</th> 
       <th>Stock</th> 
      </tr> 
      </thead> 
      <tbody> 
      <tr *ngFor="#resource of resources | async"> 
       <td>{{resource.name}}</td> 
       <td> 
        <div class="form-group"> 
         <input type="number" class="form-control" [(ngModel)]="resource.stock" (change)="saveResource(resource._id)"> 
        </div> 
       </td> 
      </tr> 
      </tbody> 
      </table> 
     </div> 
    </div> 
    `, 
    providers: [HTTP_PROVIDERS, ResourceService] 
}) 

export class Test { 

    private searchTermStream = new Subject<string>(); 

    private resources: Observable<Resource[]> = this.searchTermStream 
     .debounceTime(500) 
     .distinctUntilChanged() 
     .switchMap((value: string) => 
      value.length > 0 ? this.resourceService.searchResources(value) : Observable.of([])) 

    private resourceToSave: Resource; 

    constructor (private resourceService: ResourceService) {} 

    search(value: string) { 
     this.searchTermStream.next(value); 
    } 

    saveResource (resourceId) { 
     // this.resourceToSave = do something with 'this.resources' and 'resourceId' 
     this.resourceService.updateResource(this.resourceToSave) 
      .subscribe(); 
    } 
} 

bootstrap(Test); 

你为什么不能直接提供resource,因为你从ngFor循环调用saveResource方法:

<tr *ngFor="#resource of resources | async"> 
    <td>{{resource.name}}</td> 
    <td> 
    <div class="form-group"> 
     <input type="text" class="form-control" [(ngModel)]="resource.stock" (change)="saveResource(resource)"> 
    </div> 
    </td> 
</tr> 

这样你就不必使用其ID获取资源..

saveResource (resourceToSave) { 
    this.resourceService.updateResource(resourceToSave) 
     .subscribe(); 
} 

否则就很难从observable获取资源列表。您需要将其保存到您的组件的专用属性中...

+0

我非常渴望学习。您可以添加如何从observable获取资源列表,将其保存到组件的专用属性中?这将是非常有教育意义的。 –