当我从Firebase数据库加载位置项时,我正在使用Angular 6代码,如下所示:
export class LocationService {
private locations: Observable<any[]>;
private locationsCollection: AngularFirestoreCollection<any>;
constructor(private db: AngularFirestore,
private messageService: MessageService) {
console.log('LocationService contructor triggered!!!');
this.locationsCollection = db.collection<any>('locations');
this.locations = this.locationsCollection.snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data() as Location;
const id = a.payload.doc.id;
return { id, ...data };
}))
);
}
如何访问特定项目(位置)?目前,我正在使用此代码:
getLocation(id) {
const promise = new Promise((resolve, reject) => {
this.locationsCollection.doc(id).ref.get().then(
(doc) => {
resolve(doc.data());
},
(reason) => {
console.log('Could not get the document, reason: ' + reason);
}
);
});
return promise;
}
但是,它会向Firebase服务器发出HTTP请求。我认为如果我的locations
可观察数据中包含所有数据,最好从中获取项目而不是执行冗余HTTP请求。
更新 - 修改后添加的代码
这是我服务中的新代码:
getLocation(id): Observable<any> {
console.log(id);
return this.locations
.pipe(map(
locations => locations.find(location => location.id === id)
));
}
模板中的Google地图上有一个agm标记,如下所示:
<agm-marker *ngFor="let location of locations | async"
[latitude]="location.locations[0].latitude"
[longitude]="location.locations[0].longitude"
[openInfoWindow]="true"
[title]="location.title"
(markerClick)="onMarkerClick(location.id)"
[iconUrl]="'../assets/gulicka.png'"
routerLink="admin"
[label]="V"
>
</agm-marker>
在TypeScript中单击此函数后触发:
onMarkerClick(id) {
this.router.navigate(['map', 'location', id]);
}
导致此TypeScript组件:
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Params, Router} from '@angular/router';
import {LocationService} from '../location.service';
import {Location} from '../location/location.model';
import {Observable} from 'rxjs/index';
@Component({
selector: 'app-map-detail',
templateUrl: './map-detail.component.html',
styleUrls: ['./map-detail.component.css']
})
export class MapDetailComponent implements OnInit {
location: Location;
idClicked: string;
currentLocation: Observable<Location>;
constructor(private route: ActivatedRoute,
private router: Router,
private locationService: LocationService) { }
ngOnInit() {
this.currentLocation = this.locationService.getLocation(this.idClicked).subscribe(
(value) => {
console.log(value);
},
(error) => {
console.log(error);
},
() => {
console.log('Subscription complete.');
}
);
this.route.params.subscribe(
(params: Params) => {
this.idClicked = params['id'];
console.log('About to call setLocation');
}
);
}
}
因此,在此组件中,我希望根据位置ID从服务中获取位置对象。我是Angular的新手,对Observables并不完全熟悉,但我尽力而为。谢谢你的帮助。