Google自动填充位置在Angular 2中的子组件中不起作用

Sho*_*ate 6 javascript google-places-api angular2-directives angular

我正在使用googleplace指令为Google放置autocompletor.当我在AppComponent中使用此指令时,它在链接中显示,但在我在子组件中使用它时不起作用.

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)
];
Run Code Online (Sandbox Code Playgroud)

main.ts 在此输入图像描述

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


bootstrap(AppComponent,[appRouterProviders]);
Run Code Online (Sandbox Code Playgroud)

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 {

}
Run Code Online (Sandbox Code Playgroud)

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"]);
        }
}
Run Code Online (Sandbox Code Playgroud)

base.html文件已经<router-outlet></router-outlet>有它的内容

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);
       }
}
Run Code Online (Sandbox Code Playgroud)

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() {
  }
}
Run Code Online (Sandbox Code Playgroud)

的index.html 在此输入图像描述

输出: 在此输入图像描述

更新:

发现,当项目中有一个路由器插座标签时,它可以正常工作,但是当我们有嵌套路由器插座时无法工作,如上例所示嵌套路由器插座

Github链接在这里

指令代码与组件的子组件有什么问题吗?请告诉我如何解决此问题.

Joh*_*Siu 2

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

索引.html

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&sensor=false"></script>
Run Code Online (Sandbox Code Playgroud)

将您的 google API 密钥替换为 API_KEY。

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

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

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