Rxjs Angular 2异步管道工作一次

时间:2016-05-23 09:55:18

标签: angular rxjs

我尝试在我的项目上执行异步管道,但这确实是第一次正常工作。

在我的http.get完全没有返回任何内容之后...... 所以我想了解我做错了什么,因为现在我完全陷入了困境。

(我没有可用的JSONP网络服务,我认为我在这里有一个pb,但通常这是相同的)

我的服务代码:

getLocation(query: string): Observable<Array<Prediction>> {
    console.log("[call getLocation]")
    let headers = new Headers();
    this.locationUrl = this.locationUrl+"?location="+query;
    headers.append("Accept","application/json");
    return this.http.get(this.locationUrl, {headers: headers})
        .switchMap(this.extractData)
        .catch(this.handleError);
}

我的组件代码:

predictions: Observable<Array<Prediction>>;


constructor(
    private _router: Router,
    private _EventCreationService: EventCreationService,
    private _LocationService: LocationService) {

    console.log("[constrct]")
    predictions = this.term.valueChanges
        .debounceTime(500)
        .distinctUntilChanged()
        .switchMap((term:string): Observable<Array<Prediction>> => {
            console.log("[changed called]"+term)
            return this._LocationService.getLocation(term)
        })
    );
}

并在我的HTML中使用它来获取数据:

*ngFor="#item of predictions |async"

所以我认为这是我的位置服务并非从第一个事件中取消订阅,但这就是我使用switchmap的原因......但它似乎无效。

编辑: 她是extractData和handleError的代码:

 private extractData(res: Response): Array<Prediction> {
    if (res.status < 200 || res.status >= 300) {
        throw new Error('Bad response status: ' + res.status);
    }
    let body = res.json();
    let result : Array<Prediction> = new Array<Prediction>();
    result.push(body.predictions);
    console.log("-->"+JSON.stringify(body))
    return result;
}

private handleError (error: any) {
   // In a real world app, we might send the error to remote logging infrastructure
   let errMsg = error || 'Server error';
   console.error(JSON.stringify(errMsg)); // log to console instead
   return Observable.throw(errMsg);
}

我开始想知道它是否可能是我的角度2或rxjs版本的错误....

2 个答案:

答案 0 :(得分:1)

我在getLocation方法中看到了错误。它不是switchMap运算符,而是map运算符:

getLocation(query: string): Observable<Array<Prediction>> {
  (...)
  return this.http.get(this.locationUrl, {headers: headers})
    .map(this.extractData) // <-----------
    .catch(this.handleError);
}

答案 1 :(得分:0)

而不是switchMap使用flatMap将可观察序列的每个元素投射到另一个可观察序列。

如果您想要取消之前的观察信息,请使用flatMapLatest