Angular 2,在收到坐标时订阅

时间:2017-02-27 20:58:12

标签: javascript angular rxjs angular2-observables

我正在学习Angular 2.我使用带有Observable的LocationService,在一段时间后将坐标交给我。这是我的代码。

location.service.ts

public getLocation(): Observable<any> {
    return Observable.create(observer => {
        if(window.navigator && window.navigator.geolocation) {
            window.navigator.geolocation.getCurrentPosition(
                (position) => {
                    observer.next(position);
                    observer.complete();
                },
                (error) => observer.error(error)
            );
        } else {
            observer.error('Unsupported Browser');
        }
    });
}

app.component.ts

ngOnInit() {
    this.location.getLocation().subscribe((coordinates) => {
        this.lat = coordinates.coords.latitude;
        this.lng = coordinates.coords.longitude;
    });
}
  

我如何订阅接收坐标以便我可以在第一次订阅时收到地图,添加标记 ..

1 个答案:

答案 0 :(得分:3)

首先,我会将该方法放入服务中。

所以说你有一个名为location.service.ts的文件,其中export class LocationService位于此文件中,您将拥有以下内容

getLocation(): Observable<any> {
    return Observable.create(observer => {
        if(window.navigator && window.navigator.geolocation) {
            window.navigator.geolocation.getCurrentPosition(
                (position) => {
                    observer.next(position);
                    observer.complete();
                },
                (error) => observer.error(error)
            );
        } else {
            observer.error('Unsupported Browser');
        }
    });
}

在你的组件中,你会做这样的事情:

import { Component, OnInit } from '@angular/core';
import { LocationService } from '/shared/location.service.ts';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implments OnInit {

  constructor(private service: LocationService) {}

   ngOnInit(){
     this.service.getLocation().subscribe(rep => {
        // do something with Rep, Rep will have the data you desire.
     });
   }
}