如何设置从angular6调用autocomplete google map api的去Bounce时间

如何设置从angular6调用autocomplete google map api的去Bounce时间,angular,google-maps,google-maps-api-3,angular6,googleplacesautocomplete,Angular,Google Maps,Google Maps Api 3,Angular6,Googleplacesautocomplete,我已经制定了一个自定义指令来使用GoogleAPI自动完成功能,并试图减少对google的api调用次数 这是我的密码 请建议我设置一些延迟,以减少对谷歌服务器的api调用,从而实现输入自动完成功能 这段代码按字母输入调用api,我想在4到5秒后或键入一个单词后进行输入 //Google-place-directive.ts import { Directive, ElementRef, OnInit, Output, EventEmitter } from "@angula

我已经制定了一个自定义指令来使用GoogleAPI自动完成功能,并试图减少对google的api调用次数 这是我的密码

请建议我设置一些延迟,以减少对谷歌服务器的api调用,从而实现输入自动完成功能

这段代码按字母输入调用api,我想在4到5秒后或键入一个单词后进行输入

//Google-place-directive.ts

import {
  Directive,
  ElementRef,
  OnInit,
  Output,
  EventEmitter
} from "@angular/core";

declare var google: any;

@Directive({
  selector: "[google-place]"
})
export class GooglePlacesDirective implements OnInit {
  @Output() onSelect: EventEmitter<any> = new EventEmitter();
  private element: HTMLInputElement;

  constructor(elRef: ElementRef) {
    //elRef will get a reference to the element where
    //the directive is placed
    this.element = elRef.nativeElement;
  }

  getFormattedAddress(place) {
    //@params: place - Google Autocomplete place object
    //@returns: location_obj - An address object in human readable format
    let location_obj = {};
    console.log(place);
    console.log(place.geometry.location.lat());
    console.log(place.geometry.location.lng());
    for (let i in place.address_components) {
      let item = place.address_components[i];

      location_obj["formatted_address"] = place.formatted_address;
      if (item["types"].indexOf("locality") > -1) {
        location_obj["locality"] = item["long_name"];
      } else if (item["types"].indexOf("administrative_area_level_1") > -1) {
        location_obj["admin_area_l1"] = item["short_name"];
      } else if (item["types"].indexOf("street_number") > -1) {
        location_obj["street_number"] = item["short_name"];
      } else if (item["types"].indexOf("route") > -1) {
        location_obj["route"] = item["long_name"];
      } else if (item["types"].indexOf("country") > -1) {
        location_obj["country"] = item["long_name"];
      } else if (item["types"].indexOf("postal_code") > -1) {
        location_obj["postal_code"] = item["short_name"];
      }
    }
    return location_obj;
  }

  ngOnInit() {
    const autocomplete = new google.maps.places.Autocomplete(this.element);
    //Event listener to monitor place changes in the input
    google.maps.event.addListener(autocomplete, "place_changed", () => {
      //Emit the new address object for the updated place
      this.onSelect.emit(this.getFormattedAddress(autocomplete.getPlace()));
    });
  }
}
//html就像

 <input
                type="text"
                class="google-place-input"
                google-place
                (onSelect)="setAddress($event)"
                placeholder="Type to search.."
              />

提前感谢

从事件创建一个可观察对象,然后应用debounceTime操作符

顺便说一下,4-5秒太长了。去盎司时间是最后一次按键后的时间

更新1 尝试在用户键入查询的输入上添加以下指令

去盎司时间指令.ts your-template.html
我试过这样的方法:const autocomplete=new google.maps.places.Autocompletethis.element//用于监视输入中的位置更改的事件侦听器\n//创建发出“place_changed”事件的可观察对象const source=fromEventautocomplete,“place_changed”//映射到具有给定事件时间戳const example=source.pipedebounceTime4000的字符串;const subscribe=example.subscribebeval=>console.logval;//我得到了一个类型错误error:Invalid event target at setupSubscription fromEvent.js:50 at Observable.\u subscribe fromEvent.js:24非常感谢您的时间,我得到了逻辑,但我仍然很困惑,我如何将这个输入逻辑与GOOGle autocomplete API一起使用,比如const autocomplete=newgoogle.maps.places.autocompletethetis.element//事件侦听器,用于监视输入google.maps.Event.addListenerautocomplete中的位置更改,place_changed,=>{//Emit this.onSelect.emitthis.getFormattedAddressautocomplete.getPlace;};提前谢谢
import { fromEvent } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

//create observable that emits 'place_changed' events
const source = fromEvent(autocomplete, 'place_changed');

//map to string with given event timestamp
const example = source.pipe(debounceTime(4000));

const subscribe = example.subscribe(val => console.log(val));
import {AfterViewInit, Directive, ElementRef, forwardRef, Input, OnDestroy, Renderer2} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {fromEvent, Subject} from 'rxjs';
import {debounceTime, takeUntil} from 'rxjs/operators';

// tslint:disable:directive-selector
@Directive({
  selector: '[debounceTime]',
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => DebounceTimeDirective),
    multi: true
  }]
})
export class DebounceTimeDirective extends Destroyable implements ControlValueAccessor, AfterViewInit, OnDestroy {
  protected destroyed$ = new Subject<boolean>();

  @Input()
  debounceTime: number;

  onChange = (_) => {};
  onTouched = () => {};

  constructor(private _elementRef: ElementRef, private renderer: Renderer2) {
    super();
  }

  ngAfterViewInit() {
    fromEvent(this._elementRef.nativeElement, 'keyup')
      .pipe(
        takeUntil(this.destroyed$),
        debounceTime(this.debounceTime)
      )
      .subscribe((event: any) => {
        this.onChange(event.target.value);
      });
  }

  ngOnDestroy(): void {
    this.destroyed$.next(true);
    this.destroyed$.complete();
  }

  writeValue(value: any): void {
    const normalizedValue = value === null || value === undefined ? '' : value;
    this.renderer.setProperty(this._elementRef.nativeElement, 'value', normalizedValue);
  }

  registerOnChange(fn: () => any): void { this.onChange = fn; }
  registerOnTouched(fn: () => any): void { this.onTouched = fn; }
}
<input [debounceTime]="4000" ... />