Как правильно сделать сервис?
Доброго дня-утра-вечера
Начал копать Angular2 и вот завис: Не получается сделать сервис. Такое впечатление, что он не отрабатывает вообще Помогите пжалста, кто не сильно занят...:help: //app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpModule } from '@angular/http'; import { Settings} from './settings'; import { CurrentLocationService } from './current-location.service'; import { AppComponent } from './app.component'; import { HeaderComponent } from './header/header.component'; import { GeolocationComponent } from './geolocation/geolocation.component'; import { GetweatherService } from './getweather.service'; import { GetcityComponent } from './getcity/getcity.component'; @NgModule({ declarations: [ AppComponent, HeaderComponent, GeolocationComponent, GetcityComponent ], imports: [ BrowserModule, HttpModule ], providers: [GetweatherService,CurrentLocationService], bootstrap: [AppComponent] }) export class AppModule { } //current-location.service.ts import { Injectable } from '@angular/core'; @Injectable() export class CurrentLocationService { mylocation = {}; CurrentPosition() { if(navigator.geolocation){ navigator.geolocation.getCurrentPosition(this.setP osition.bind(this)); }; console.log('ок'); // ВОТ этого в логах нет... } private setPosition(position){ this.mylocation = position.coords; } } вызываю сервис например здесь //geolocation.components.ts import { Component, Input, OnInit } from '@angular/core'; import { CurrentLocationService } from '../current-location.service'; @Component({ selector: 'app-geolocation', templateUrl: './geolocation.component.html', styleUrls: ['./geolocation.component.scss'], }) export class GeolocationComponent implements OnInit { constructor(private _currentlocationservice: CurrentLocationService) {} ngOnInit() { var location = this._currentlocationservice.mylocation; } } |
mrmammoth,
конструктор добавь в сервис свой |
Спасибо, помогло.
Ещё не поможете малость? //geolocation.component.ts import { Component, Input, OnInit } from '@angular/core'; import { GetlocationService } from '../getlocation.service'; @Component({ selector: 'app-geolocation', templateUrl: './geolocation.component.html', styleUrls: ['./geolocation.component.scss'], }) export class GeolocationComponent implements OnInit { constructor( private _getlocationservice: GetlocationService) { } myLocation={}; ngOnInit() { this._getlocationservice.getCurrentPosition().subscribe( data => {this.myLocation = data}, error => console.log('Error fetching data')); console.log(this.myLocation) } } //geolocation.component.html <p>{{myLocation.coords.latitude}} , {{myLocation.coords.longitude}}</p> Координаты на странице отображаются, но в лог вываливает вот такое: ERROR TypeError: _co.myLocation.coords is undefined Stack trace: View_GeolocationComponent_0/<@ng:///AppModule/GeolocationComponent.ngfactory.js:11:9 updateRenderer@http://localhost:4200/vendor.bundle.js:56763:61 checkAndUpdateView@http://localhost:...ndor.bundle.js:56282:5 callViewAction@http://localhost:4200/vendor.bundle.js:56642:21 execComponentViewsAction@http://loca...ndor.bundle.js:56574:13 checkAndUpdateView@http://localhost:...ndor.bundle.js:56283:5 callViewAction@http://localhost:4200/vendor.bundle.js:56642:21 execComponentViewsAction@http://loca...ndor.bundle.js:56574:13 checkAndUpdateView@http://localhost:...ndor.bundle.js:56283:5 callViewAction@http://localhost:4200/vendor.bundle.js:56642:21 execComponentViewsAction@http://loca...ndor.bundle.js:56574:13 checkAndUpdateView@http://localhost:...ndor.bundle.js:56283:5 ../../../core/@angular/core.es5.js/</ViewRef_.prototype.detectChanges@http://localhost:4200/vendor.bundle.js:54203:9 ../../../core/@angular/core.es5.js/</ApplicationRef_.prototype.tick/<@http://localhost:4200/vendor.bundle.js:48834:58 ../../../core/@angular/core.es5.js/</ApplicationRef_.prototype.tick@http://localhost:4200/vendor.bundle.js:48834:13 ../../../core/@angular/core.es5.js/</ApplicationRef_.prototype._loadComponent@http://localhost:4200/vendor.bundle.js:48809:9 ../../../core/@angular/core.es5.js/</ApplicationRef_.prototype.bootstrap@http://localhost:4200/vendor.bundle.js:48797:9 ../../../core/@angular/core.es5.js/</PlatformRef_.prototype._moduleDoBootstrap/<@http://localhost:4200/vendor.bundle.js:48568:74 ../../../core/@angular/core.es5.js/</PlatformRef_.prototype._moduleDoBootstrap@http://localhost:4200/vendor.bundle.js:48568:13 ../../../core/@angular/core.es5.js/</PlatformRef_.prototype._bootstrapModuleFactoryWith Zone/</</<@http://localhost:4200/vendor.bundle.js:48530:21 ../../../../zone.js/dist/zone.js/</</ZoneDelegate.prototype.invoke@http://localhost:4200/polyfills.bundle.js:2937:17 onInvoke@http://localhost:4200/vendor.bundle.js:47912:24 ../../../../zone.js/dist/zone.js/</</ZoneDelegate.prototype.invoke@http://localhost:4200/polyfills.bundle.js:2936:17 ../../../../zone.js/dist/zone.js/</</Zone.prototype.run@http://localhost:4200/polyfills.bundle.js:2687:24 scheduleResolveOrReject/<@http://localhost:4200/polyfills.bundle.js:3389:52 ../../../../zone.js/dist/zone.js/</</ZoneDelegate.prototype.invokeTask@http://localhost:4200/polyfills.bundle.js:2970:17 onInvokeTask@http://localhost:4200/vendor.bundle.js:47903:24 ../../../../zone.js/dist/zone.js/</</ZoneDelegate.prototype.invokeTask@http://localhost:4200/polyfills.bundle.js:2969:17 ../../../../zone.js/dist/zone.js/</</Zone.prototype.runTask@http://localhost:4200/polyfills.bundle.js:2737:28 drainMicroTaskQueue@http://localhost...ills.bundle.js:3147:25 в чём беда?:-? |
<p>{{myLocation.coords?.latitude}} , {{myLocation.coords?.longitude}}</p> |
Спасибо
|
И ещё, надеюсь крайняя на сей момент проблема: служба в службу
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import { Settings} from './settings'; import { GetlocationService } from './getlocation.service'; @Injectable() export class GetweatherService { constructor(private http: Http, private _getlocationservice: GetlocationService) {} coordData: any; getWeatheritemsbyCoords(): Observable<any>{ this._getlocationservice.getCurrentPosition().subscribe( data => {this.coordData = data}, error => console.log('Error fetching geolocation data')); console.log(this.coordData) return this.http.get(Settings.BaseURL+'?lat='+this.coordData.coords.latitude+'&lon='+this.coordData.coords.longitude+'&APPID='+Settings.APPID) .map(response => response.json()); //return this.http.get(Settings.BaseURL+'?lat='65.785645&lon=33.106754&APPID='+Settings.APPID) //.map(response => response.json()); - Так работает } } лог: ERROR TypeError: this.coordData is undefined Если можно?... |
mrmammoth,
Добро пожаловать на грабли асинхронного программирования :) |
ок. погуглил и сделал запрос с задержкой
(некрасиво, конечно. надо бы ждать не 5 сек а получение координат. но пока хоть так) import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/Rx'; import { IntervalObservable } from 'rxjs/observable/IntervalObservable'; import { Settings} from './settings'; import { GetlocationService } from './getlocation.service'; @Injectable() export class GetweatherService { coordData: any; constructor(private http: Http, private _getlocationservice: GetlocationService) {} getCurrentCoords(){ this._getlocationservice.getCurrentPosition().subscribe( data => {this.coordData = data}, error => console.log('Error fetching geolocation data')); } getWeatherbyCoordsIntrval(){ return IntervalObservable .create(5000) .flatMap(() => { return this.http.get(Settings.BaseURL+'?lat='+this.coordData.coords.latitude+'&lon='+this.coordData.coords.longitude+'&APPID='+Settings.APPID) .map(response => response.json()); }); } } import { Component, OnInit } from '@angular/core'; import { GetweatherService } from '../getweather.service'; @Component({ selector: 'app-getplace', templateUrl: './getplace.component.html', styleUrls: ['./getplace.component.scss'] }) export class GetplaceComponent implements OnInit { weatherData: any[]; constructor(private _getweatherservice: GetweatherService) { } ngOnInit() { this._getweatherservice.getWeatherbyCoordsIntrval() .subscribe( data => {this.weatherData = data}, error => console.log('Error fetching weather data')); } } теперь не могу получить данные Error fetching weather data |
mrmammoth,
не вижу, чтобы getCurrentCoords() где-то вызывалось. |
ой:)
вот так работает. спасибо getWeatherbyCoordsIntrval(){ this._getlocationservice.getCurrentPosition().subscribe( data => {this.coordData = data}, error => console.log('Error fetching geolocation data')); return IntervalObservable .create(500) .flatMap(() => { return this.http.get(Settings.BaseURL+'?lat='+this.coordData.coords.latitude+'&lon='+this.coordData.coords.longitude+'&APPID='+Settings.APPID) .map(response => response.json()); }); } } |
Часовой пояс GMT +3, время: 07:48. |