2017-02-27 2 views
0

각도 2를 배우고 있습니다. 얼마 후에 좌표를 건네주는 Observable과 함께 LocationService를 사용하고 있습니다. 이것은 내 코드입니다.각도 2, 좌표를 수신 할 때 구독하십시오.

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

먼저이 메소드를 서비스에 넣습니다.

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. 
    }); 
    } 
} 
+0

:

그래서 당신은 당신이 구성 요소에있어 내부 다음

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'); } }); } 

당신이 뭔가를 할 수 있습니다해야이 파일 내부의 export class LocationService으로 location.service.ts라는 파일이 있다고 가정 해 고맙습니다! 그것은 사실입니다. 내 app.component 코드를 추가하겠습니다. – Notflip

+0

@Notflip 방금 답변을 업데이트했습니다. –

+0

내 코드에서 app.component에 coords lat 및 lng 변수를 설정 했으므로 권장 할 만합니까? 지도에 대해 새로운 listerener/observable를 만드시겠습니까? 또는 첫 번째 인스턴스를 구독 할 때 모든 논리를 수행하면됩니다. 지저분한 코드 같아요, 안 그래요? – Notflip