我使用的是Angular 2.0.0-beta.0和TypeScript 1.7.5
在班级saveResource
的方法Test
中,需要从resourceId
类型this.resources
中提取Observable<Resource[]>
的资源,并将其分配给this.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);
答案 0 :(得分:2)
为什么不能直接提供resource
,因为您从saveResource
循环调用ngFor
方法:
<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获取资源列表。您需要将其保存到组件的专用属性中......