我正试图在我的ngFor
中迭代我的结果 - 它不像Angular 1那么直观。我有以下内容:
search.service.ts
import {Injectable} from 'angular2/core';
import {Http, HTTP_PROVIDERS, Response} from 'angular2/http';
import 'rxjs/add/operator/map';
@Injectable()
export class SearchService {
constructor( private _http: Http ) {
}
DoGeneralSearch(s){
return this._http.get('http://localhost:6000/search?q=' + s)
.map((res:Response) => res.json())
}
}
typeahead.ts
import {Component, Input, OnChanges} from "angular2/core";
import {SearchService} from "../../../services/search.service";
@Component({
selector: "typeahead",
providers: [SearchService],
template : `
<div>{{searchSvc | async | json}}</div>
<div id="typeaheadRooms" *ngIf="searchSvc">
<div class="typeaheadRowRooms" *ngFor="#item of searchSvc?.rooms">
<div class="typeaheadRoomTitle">{{item.name}}}</div>
</div>
<div class="typeaheadRowRooms" *ngFor="#item of searchSvc?.colors">
<div class="typeaheadRoomTitle">{{item.name}}}</div>
</div>
`,
})
export class TypeaheadComponent implements OnChanges {
@Input() txt: string;
display = false;
ngOnChanges(changes: {[propName: string]: SimpleChange}) {
var search = changes['txt'].currentValue;
if(search.length > 2) {
this.display = true;
this.searchSvc = this._searchService.DoGeneralSearch(search);
}
else
{
this.display = false;
}
}
constructor(private _searchService: SearchService) {}
}
json中的典型结果:
{
"max":20,
"queryString":"chem",
"rooms":[
{
"name":"Lima"
},
{
"name":"Delta"
}
],
"colors":[
{
"name":"Red"
},
{
"name":"Lime"
}
]
}
发生了什么事?好吧,{{searchSvc | async | json}}
告诉我结果。
但是ngFor
:否:(
任何线索?谢谢你提前!!!
答案 0 :(得分:1)
在这种情况下,您需要使用:
<div class="typeaheadRowRooms" *ngFor="#item of searchSvc | async">
并按照以下方式更新您的服务:
DoGeneralSearch(s){
return this._http.get('http://localhost:6000/search?q=' + s)
.map((res:Response) => res.json().rooms);
}
修改强>
如果你想从observable接收完整的对象,我会看到两种方法:
明确订阅:
this._searchService.DoGeneralSearch(search).subscribe(
(data) => {
this.searchSvc = data;
}
);
并在模板中
<div class="typeaheadRowRooms" *ngFor="#item of searchSvc?.rooms">
自定义管道以获取rooms
数据:
@Pipe({name: 'field'})
export class FieldPipe implements PipeTransform {
transform(value, args:string[]) : any {
return value[args[0]];
}
}
并在模板中
<div class="typeaheadRowRooms" *ngFor="#item of searchSvc | async | field:rooms">