Angular 6 http.get订阅无需查询api就可以获取相同的数据

爱丹曼

我正在尝试使用我的来自角度的节点api进行搜索查询。我正在订阅api调用http get请求,并在第一时间获取了正确的数据。在更新了参数之后的第二个请求中,它在订阅中返回了相同的数据,而该调用从未在API端收到?如何获得订阅以显示新数据并进行更新的api调用?我正在使用angular 6.0.9和rxjs 6.2.2

api.ts

@Injectable()
export class API {
  public apiBase = '';
  headers = new HttpHeaders();
  options: any;

  constructor(public http: HttpClient) {
    this.apiBase = environment.api;
    this.headers.append('Content-Type', 'application/json');
    this.options = {
      headers: this.headers
    };
  }

  searchProperties(data: any): Observable<any> {
    let params = {}
    for(var d in data) {
      params[d] = JSON.stringify(data[d]);
    }
    return this.http.get(this.apiBase + '/properties/search', {params: params})
      .catch(this.handleError);
  }

}

search.component.ts

ngOnInit() {
  // works fine here with new data
  this.searchQuery();
}

searchQuery() {
  this.api.searchProperties(this.searchData)
    .map(result => {
        console.log('map: ', result);
        }
    })
    .subscribe(res => {
        console.log(res);
    });
}

searchAgain(lat, lng) {
  // calls the query and gets all the way to the api call and returns the same data as the previous call without hitting the api at all.
  this.searchData.lat = lat;
  this.searchData.lng = lng;
  this.searchQuery();
}
亚历山大·列昂诺夫(Alexander Leonov)

在这种情况下,使用rxjs'Subject按需发出新的搜索参数,并使用诸如switchMap()或的方式将http调用混入此管道中会更加清晰和方便flatMap()同样,通过这种方式,您不必手动管理多个订阅尝试-顺便说一句,理想情况下您应该这样做,但您不必这样做。全部开始时,只会进行一个订阅。我建议类似下面的代码。

要做的另一件事是检查浏览器控制台中是否存在与代码相关的任何错误。似乎应该有其他阻止它通过的东西。我已经写了很多这样的代码,它始终可以正常工作。因此,如果此建议不起作用,则意味着您在提供的代码之外还有其他东西会使该事情发生异常……但是,几乎没有任何人能够猜测问题出在哪里-除非您提供一个最小,完整和可验证的示例而且我认为,在这种非常简单的情况下,您只需准备一个示例就可以解决您的问题。

private searchParams = new Subject();

ngOnInit() {
  // works fine here with new data
  this.searchQuery();
}

searchQuery() {
    this.searchParams.pipe(
        startWith(<whatever_default_search_params_are>),
        switchMap(params => this.api.searchProperties(params))
    ).subscribe(res => {
        console.log(res);
    });
}

searchAgain(lat, lng) {
  this.searchParams.next({lat: lat, lng: lng});
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章