kittycatbytes kittycatbytes - 6 months ago 23
TypeScript Question

RxJs Help in Angular / SharePoint Search HTTP Call

I have done a great deal of work trying to refactor this method (and maybe this is as simple as it can get). I am calling a SharePoint Search Query API, which is returned in a strange JSON way (nested and nested - example below code). This code simplifies it to optimize for consumption in an Angular ngFor. However, I am hoping to get some insight on how I could simplify this, as I am still struggling with RxJs. TIA!

getSearchQuery(term) {
return this.http.get(this.variables.spUrl + this.queryAPI + '%27' + term + this.queryOptions + '%27', this.options)
.map(res => res.json().d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results)
.map(data => data.map(item => item.Cells.results))
.map((data, i) => {
data.map((object, i) => {
this.newProp = {};
object
.map(prop => {
let key = prop.Key;
let value = prop.Value;
this.newProp[key] = value;
});
object = this.newProp;
this.newData.push(object);
});
console.log(this.newData);
return this.newData;
})
.share()


}

Code that console.logs the image attached below:

getSearchQuery(term) {
return this.http.get(this.variables.spUrl + this.queryAPI + '%27' + term + this.queryOptions + '%27', this.options)
.map(res => res.json().d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results)
.map(data => data.map(item => item.Cells.results))
.do(data => console.log(data))
}


enter image description here

Answer Source

Like this:

getSearchQuery(term: string) {
  const url = `${this.variables.spUrl}${this.queryAPI}%27${term}${this.queryOptions}%27`;
  return this.http.get(url, this.options)
    .map(res => res.json().d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results)
    .map(rowResults => rowResults.map(item => item.Cells.results))
    .map(this.remapResults)
    .do(data => console.log(data)) // Do whatever you want with new data.
    .share();
}

remapResults(results:  any[]) {
  return results.map(object => {
    const newProp = {};
    for (const prop of object) {
      const {Key, Value} = prop;
      newProp[Key] = Value;
    }
    return newProp;
  });
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download