谷歌自动完成位置在 Angular 2 的子组件中不起作用 [英] Google autocompleter place doesn't work in the Child Component in Angular 2

查看:19
本文介绍了谷歌自动完成位置在 Angular 2 的子组件中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 googleplace 指令用于

import { provideRouter, RouterConfig } from '@angular/router';import { BaseComponent } from './components/base/base.component';从'./components/dashboard/dashboard.component'导入{仪表板组件};const 路由:RouterConfig=[{path:"",redirectTo:"/admin",pathMatch:'full'},{path:"admin",component:BaseComponent,孩子们:[{ 路径:'',组件:BaseComponent},{ 路径:'仪表板',组件:仪表板组件},]}];导出 const appRouterProviders = [提供路由器(路线)];

ma​​in.ts

import {bootstrap} from '@angular/platform-b​​rowser-dynamic';从 './app.component' 导入 {AppComponent};从'./app.routes'导入{appRouterProviders};bootstrap(AppComponent,[appRouterProviders]);

app.component.ts

import {Component} from '@angular/core';从 '@angular/router' 导入 {ROUTER_DIRECTIVES};@成分({选择器:'我的应用',模板:`<路由器插座></路由器插座>,指令:[ROUTER_DIRECIVES]})导出类 AppComponent {}

base.component.ts

import {Component,OnInit} from '@angular/core';从@angular/router"导入 { provideRouter, RouterConfig,ROUTER_DIRECTIVES,Router };@成分({选择器:'app-base',templateUrl:"../app/components/base/base.html",指令:[ROUTER_DIRECIVES],预编译:[]})导出类 BaseComponent 实现 OnInit{构造函数(私有_路由器:路由器){}ngOnInit():any{this._router.navigate(["admin/dashboard"]);}}

base.html 有它的内容

dashboard.component.ts

import {Component,OnInit} from '@angular/core';导入 { provideRouter, RouterConfig,ROUTER_DIRECTIVES,Router } from '@angular/router';从./../../../directives/googleplace.directive"导入 {GoogleplaceDirective};@成分({选择器:仪表板",模板:`<input type="text" [(ngModel)] = "address" (setAddress) = "getAddress($event)" googleplace/>`,指令:[ROUTER_DIRECTIVES,GoogleplaceDirective]})导出类 DashboardComponent 实现 OnInit{构造函数(私有_路由器:路由器){}ngOnInit():any{//this._router.navigate(["dashboard/business"]);}公共地址:对象;获取地址(地点:对象){this.address = place['formatted_address'];var location = place['geometry']['location'];var lat = location.lat();var lng = location.lng();console.log("地址对象", place);}}

googleplace.directive

import {Directive, ElementRef, EventEmitter, Output} from '@angular/core';从@angular/common"导入 {NgModel};声明 var google:any;@指示({选择器:'[googleplace]',提供者:[NgModel],主持人: {'(输入)':'onInputChange()'}})导出类 GoogleplaceDirective {@Output() setAddress: EventEmitter

输出:

更新:

<块引用>

发现,当只有一个router-outlet标签时,效果很好在项目中,但是当我们将路由器插座嵌套为上面的例子有嵌套的 router-outlet

此处的 Github 链接

组件的子组件的指令代码是否有任何问题?请告诉我如何解决此问题.

解决方案

问题是 https://maps.googleapis.com/maps/api/place/js/AutocompletionService.GetPredictions 需要一个api 密钥,当您在路由器子节点中使用它时.

index.html

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&sensor=false"></script>

用您的 google API 密钥代替 API_KEY.

我无法解释子组件(不需要 api 密钥)和路由器子组件(需要 api 密钥)之间的行为差​​异.

根据 Google Map Api 文档,需要 API 密钥:

https://developers.google.com/maps/documentation/javascript/地点自动完成

I was using the googleplace directive for the Google places autocompletor. It works when I use this directive in AppComponent as shown in the link but doesn't work when I used it in the child Components.

app.routes.ts

import { provideRouter, RouterConfig }  from '@angular/router';

import { BaseComponent }  from './components/base/base.component';
import { DashboardComponent }  from './components/dashboard/dashboard.component';


const routes: RouterConfig=
    [
        {path:"",redirectTo:"/admin",pathMatch:'full'}, 

        {path:"admin",component:BaseComponent,
            children:[
                    { path: '', component: BaseComponent},
                    { path: 'dashboard', component: DashboardComponent},
                ]
         }

    ];


export const appRouterProviders = [
  provideRouter(routes)
];

main.ts

import {bootstrap}    from '@angular/platform-browser-dynamic';
import {AppComponent} from './app.component';
import {appRouterProviders} from './app.routes';


bootstrap(AppComponent,[appRouterProviders]);

app.component.ts

import {Component} from '@angular/core';
import {ROUTER_DIRECTIVES} from '@angular/router';


@Component({
    selector : 'my-app',
    template:  `
            <router-outlet></router-outlet>
        `    ,
        directives:[ROUTER_DIRECTIVES]
})
export class AppComponent {

}

base.component.ts

import {Component,OnInit} from '@angular/core';
import { provideRouter, RouterConfig,ROUTER_DIRECTIVES,Router }  from '@angular/router';



@Component({
    selector: 'app-base',
    templateUrl:"../app/components/base/base.html",
    directives:[ROUTER_DIRECTIVES],
    precompile:[]

})



export class BaseComponent implements OnInit{

        constructor(private _router:Router){}

        ngOnInit():any{

            this._router.navigate(["admin/dashboard"]);
        }
}

base.html has <router-outlet></router-outlet> has its content

dashboard.component.ts

import {Component,OnInit} from '@angular/core';

import { provideRouter, RouterConfig,ROUTER_DIRECTIVES,Router }  from '@angular/router';
import {GoogleplaceDirective} from './../../../directives/googleplace.directive';



@Component({
    selector: 'dashboard',
   template:`
        <input type="text" [(ngModel)] = "address"  (setAddress) = "getAddress($event)" googleplace/>
   `,
    directives:[ROUTER_DIRECTIVES,GoogleplaceDirective]
})

export class DashboardComponent implements OnInit{

        constructor(private _router:Router){}

        ngOnInit():any{

            // this._router.navigate(["dashboard/business"]);
        }

        public address : Object;
       getAddress(place:Object) {       
           this.address = place['formatted_address'];
           var location = place['geometry']['location'];
           var lat =  location.lat();
           var lng = location.lng();
           console.log("Address Object", place);
       }
}

googleplace.directive

import {Directive, ElementRef, EventEmitter, Output} from '@angular/core';
import {NgModel} from '@angular/common';

declare var google:any;

@Directive({
  selector: '[googleplace]',
  providers: [NgModel],
  host: {
    '(input)' : 'onInputChange()'
  }
})
export class GoogleplaceDirective  {
  @Output() setAddress: EventEmitter<any> = new EventEmitter();
  modelValue:any;
  autocomplete:any;
  private _el:HTMLElement;


  constructor(el: ElementRef,private model:NgModel) {
    this._el = el.nativeElement;
    this.modelValue = this.model;
    var input = this._el;
    this.autocomplete = new google.maps.places.Autocomplete(input, {});
    google.maps.event.addListener(this.autocomplete, 'place_changed', ()=> {
      var place = this.autocomplete.getPlace();
      this.invokeEvent(place);
    });
  }

  invokeEvent(place:Object) {
    this.setAddress.emit(place);
  }


  onInputChange() {
  }
}

index.html

Output:

Update:

Found that, it works perfectly when there is one router-outlet tag in the project, but fails to work when we have nested router-outlet as above example has nested router-outlet

Github link here

Is there any issue with directive code with child components of a component? Please let me know how I can resolve this issue.

解决方案

The issue is https://maps.googleapis.com/maps/api/place/js/AutocompletionService.GetPredictions require an api key, when you use it inside a router child.

index.html

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&sensor=false"></script>

Put your google API key in place of API_KEY.

I cannot explain the difference in behavior between child component(no api key needed) and router child(api key required).

According to Google Map Api documentation, API key is required:

https://developers.google.com/maps/documentation/javascript/places-autocomplete

这篇关于谷歌自动完成位置在 Angular 2 的子组件中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆