我只想在我的应用登录页面/ index / application.hbs上显示我的经度。我很尴尬地说我在这方面工作了多久!任何人都可以帮助我吗?
//geoservice.js
import Ember from 'ember';
export default Ember.Service.extend({
longitude: function(position){
return position.coords.longitude;
},
latitude: function(position){
return position.coords.latitude;
}
});
//geo-component.js
import Ember from 'ember';
export default Ember.Component.extend({
geoservice: Ember.inject.service(),
myLongitude: function(){
if (navigator.geolocation) {
return this.get('geoservice').longitude(navigator.geolocation.getCurrentPosition());
} else {
return "Geolocation is not supported by this browser.";
}
}.on('init'),
});
//application.hbs
<h2 id="title">Welcome to Ember</h2>
{{outlet}}
{{geo-component.myLongitude}}
答案 0 :(得分:3)
问题不是在组件中使用服务,而是1)Geolocation
API是异步的,2)你不像你那样渲染组件。这有效:
应用/组件/地理location.js
import Ember from 'ember';
export default Ember.Component.extend({
geo: Ember.inject.service(),
loading: true,
error: null,
latitude: null,
longitude: null,
setPosition: Ember.on('init', function() {
this.get('geo').getPosition().then((position) => {
this.set('latitude', position.latitude);
this.set('longitude', position.longitude);
this.set('loading', false);
}).catch((error) => {
this.set('error', error);
});
})
});
应用程序/服务/ geo.js
import Ember from 'ember';
export default Ember.Service.extend({
getPosition() {
return new Ember.RSVP.Promise((success, error) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error)
} else {
error( new Error("Geolocation is not supported by this browser.") );
}
}).then((position) => {
return { latitude: position.coords.latitude, longitude: position.coords.longitude };
});
}
});
应用程序/模板/组件/地理location.hbs
{{#if error}}
{{error}}
{{else if loading}}
Loading...
{{else}}
lat: {{latitude}}, long: {{longitude}}
{{/if}}
应用程序/模板/ application.hbs
<h2 id="title">Welcome to Ember</h2>
{{geo-location}}