簡體   English   中英

帶有可觀察的Angular2異步管道

[英]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僅適用於PromiseObservable ,不適用於Subscription 如果您使用map而不是subscribe ,則返回一個Observable

好吧,我想通了!

您不能使用帶有回調函數的http請求(例如geocoder.geocode),而必須使用帶有URL的http.get處理角度方式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM