g从LocationService angular2获取位置

时间:2017-09-21 15:51:38

标签: geolocation angular2-services

我有位置服务

export class MapService {
  location: Position;
   allOptions;

  ngOnInit() {
          if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(
              position => {
                this.location = position;
              }
            );
         }}}

在我的component.ts方法中,我有

let pos;
constructor(private locationService: MapService) { 
    this.pos = locationService.location;
   }

print(){
console.log(this.pos);
}

当我测试它时,我的pos是 undefined

如何从LocationService获取位置(lat,lng)

1 个答案:

答案 0 :(得分:0)

您编写服务的方式不正确,您可以阅读有关服务here的更多信息。

检查以下解决方案,

@Injectable()
export class MapService {
  location: BehaviorSubject<any> = new BehaviorSubject<any>({});

  constructor(){
     if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(
         position => {
              this.location.next(position);
          }  
        )
     }
  }
}

@Component({
  selector: 'my-app',
  template: `<h1>Hello</h1>`
})
export class AppComponent {
  constructor(private ms : MapService){
    this.ms.location.subscribe(pos =>  {
      console.log(pos);
    });
  }
}

这是Plunker !!

希望这会有所帮助!!