Pipe angular2中的高效异步调用

时间:2016-08-10 13:43:13

标签: asynchronous service angular pipe

我正在尝试通过google maps api获取经度和纬度值的地址转换。我查看了有关不纯管道(https://angular.io/docs/ts/latest/guide/pipes.html)的angular2管道示例,这确实给了我一段工作代码(纯管道结果为null)

唯一的问题是,http调用正在进行多次,因为管道不纯。数据不再更改,只需转换一次。

管道:

import {Pipe, PipeTransform} from '@angular/core';
import {Http} from '@angular/http';

@Pipe({name: 'location', pure: false})
export class LocationPipe implements PipeTransform {

private readableLocation = null;
private fetchedJson = null;
private prevUrl = '';

constructor(private http:Http) {}

transform(location:string):string {
if (location !== this.prevLoc) {
  var arr = location.split(",", 2);
  var lat = arr[0];
  console.log(lat);
  var lon = arr[1];
  console.log(lon);
  var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + lon + '&sensor=true';
  console.log(url);

    this.prevLoc = location;
    this.fetchedJson = null;
    this.http.get(url)
    .map( result => result.json() )
    .subscribe( result => this.fetchedJson = result );
  }
  if (this.fetchedJson != null) {
    return this.fetchedJson.results[0].formatted_address;
  }
  return this.fetchedJson;

 }
}

HTML:

<td>{{log.location | location}}</td>

&#39; log&#39;数据是通过服务从后端接收的:

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';

export class Log {
  _id: Object;
  username: string;
  status: boolean;
  location: string;
  modelName: string;
  searchTerm: string;
  created: number;

  static create(data){
    console.log("New log created and added to the list:");
    console.log(data);
    return new Log(data);
  }

  constructor(data){
    this._id = data._id;
    this.username = data.username;
    this.status = data.status;
    this.location = data.location;
    this.modelName = data.modelName;
    this.searchTerm = data.searchTerm;
    this.created = data.created;
  }
}

@Injectable()
export class LogService {

  public logs;

  constructor(private http: Http){

    this.logs = http.get('https://arest-api.herokuapp.com/users?userStatus=true')
      .map(res => res.json())
      .map(rawUsers => rawUsers.map(Log.create));
  }
}

log.location包含字符串格式的lon和lat值:&#34; 51.993398,4.386851&#34;

加载和显示数据需要几秒钟,尽管它只包含2条记录。 是否有更好/更快/更有效的方法来获得相同的结果?

非常感谢你的帮助!如果需要更多信息,请告诉我。

编辑:仅在两个请求中提升缓存结果。虽然问题仍然是能否以更好/更有效的方式实施?不纯的管道仍被多次调用,而数据不会改变。

0 个答案:

没有答案