[英]Angular2 async pipe with observable
我尝试通过异步管道消耗一个可观察对象,这是我的模板:
<input #address type="text" id="address" placeholder="{{placeHolder}}" (keyup)="addTerm(address.value)" />
<div *ngFor="let place of possiblesPlaces | async">
{{place.label}}
</div>
这是组成部分:
export class LocationFieldComponent implements OnInit{
private searchTerms = new Subject<string>();
@Input()
placeHolder:string;
possiblesPlaces:Observable<Array<{label:string,value:any}>>;
addTerm(address:string) {
this.searchTerms.next(address);
}
ngOnInit(): void {
this.possiblesPlaces=this.searchTerms.filter(t=>t.length>2).debounceTime(300).distinctUntilChanged()
.flatMap(term =>
Observable.of(this.fetchResults(term))
)
.catch(error => {
// TODO: real error handling
console.log(error);
return Observable.of([]);
});
this.possiblesPlaces.subscribe(val => console.log(val))
}
fetchResults(address:string) :Array<{label:string,value:any}> {
var result=new Array;
var geocoder = new google.maps.Geocoder();
console.log("search with"+address);
geocoder.geocode( { 'address': address}, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
for(let i=0;i<results.length;i++){
result.push( {label:results[i].formatted_address,value:null});
}
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
});
return result;
}
}
我可以在控制台上看到observablePlaces的所有新值,但异步管道不会显示任何结果。
有时在地址字段中输入新字母时,我可以在半秒钟内看到先前可观察值的结果,但我不明白为什么?
编辑:我发现如果我等20秒,结果正确显示。 向Google API的请求很快,但是异步管道似乎需要一段时间。 有想法吗?
这应该工作
fetchResults(address:string) :Array<{label:string,value:any}> {
var subj = new Subject();
var geocoder = new google.maps.Geocoder();
console.log("search with"+address);
geocoder.geocode( { 'address': address}, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
for(let i=0;i<results.length;i++){
subject.next( {label:results[i].formatted_address,value:null});
}
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
});
return subj.asObservable();
}
ngOnInit(): void {
this.possiblesPlaces=this.searchTerms.filter(t=>t.length>2).debounceTime(300).distinctUntilChanged()
.flatMap(term =>
this.fetchResults(term).scan([], acc, x) => acc.concat(x));
)
.catch(error => {
// TODO: real error handling
console.log(error);
return Observable.of([]);
});
this.possiblesPlaces.map(val => console.log(val))
}
fetchResults()
返回一个可观察值。 在您的问题中,您返回一个空数组,然后仅在Geocoder的响应到达时才填充它。 看起来不太可靠。
ngOnInit()
使用this.possiblePlaces.subscribe()
但subscribe
回报Subscription
不是一个Observable
和| async
| async
仅适用于Promise
和Observable
,不适用于Subscription
。 如果您使用map
而不是subscribe
,则返回一个Observable
。
好吧,我想通了!
您不能使用带有回调函数的http请求(例如geocoder.geocode),而必须使用带有URL的http.get处理角度方式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.