Angular如何在找到用户位置后加载组件



我想延迟组件的加载,直到找到用户的位置。我定义了一个子路由。这个项目有一张地图和一个信息面板。地图和信息面板使用纬度和经度。我使用了传单地图。我创建了一个解析器,但没有像我预期的那样工作。这里,'geo'返回undefined。错在哪里?

<div class="container-fluid h-100">
<div class="row h-100">
<div class="col-lg-7">
<app-map></app-map>
</div>
<div class="col-lg-5 h-100">
<div class="tab-content">
<router-outlet></router-outlet>
</div>
</div>
</div>
</div>

export const appRoutes: Route[] = [
{
path: 'info', component: InfoComponent, resolve: {geo: GeolocationService}, children: [
{path: 'register', component: RegisterComponent},
{path: 'list', component: ListComponent}
]
}];

<地理位置服务/strong>

export class GeolocationService implements Resolve<any> {
constructor() {
}
resolve(): Observable<any> {
return this.findLocation();
}
findLocation = () => {
let coords;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
if (position.coords) {
coords = {lat: position.coords.latitude, lng: position.coords.longitude};
return coords;
} else {
coords = {lat: 11, lng: 11};
return coords;
}
});
} else {
coords = {lat: 11, lng: 11};
return coords;
}
};
}

InfoComponent

export class InfoComponent implements OnInit {
constructor() {
}
ngOnInit(): void {
this.route.data.subscribe(data => {
console.log('data', data);
});
}
}

我甚至会怀疑代码是否可以编译。你应该从findLocation返回一个Promise,否则什么都不会发生。

export class GeolocationService implements Resolve<any> {
resolve(): Promise<{lat: number, lng:number}> {
return new Promise((resolve,reject) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
if (position.coords) {
resolve({lat: position.coords.latitude, lng: position.coords.longitude});
} else {
reject(new Error('browser did not return coordinates'));
}
});
} else {
reject(new Error('browser does not support geolocation api'));
}
});
}
}

相关内容

  • 没有找到相关文章

最新更新