如何在离子3中使用geofire的正确方法,Im使用离子3.5火基:“4.1.3”,“geofire”:“4.1.2”,“angularfire2”:“4.0.0-rc.1”,
constructor( public angularfireDatabase: AngularFireDatabase,
private geolocation: Geolocation) { }
ionViewDidLoad() {
this.geolocation.getCurrentPosition().then((resp) =>
this.geoQuery= this.geoFire.query({
center: [resp.coords.latitude, resp.coords.longitude],
radius: 20 //kilometers
});
this.geoQuery.on("key_entered", function (key, location, distance) {
console.log('from geofire ' +location, ' key ' + key,distance);
this.angularfireDatabase.object('/products/'+key).subscribe((product) => {
this.products.push(product);
});
});
}).catch((error) => {
console.log('Error getting location', error);
});
}
返回此错误
ERROR TypeError: Cannot read property 'angularfireDatabase' of undefined
at products.ts:76
at geofire.js:685
geofire.d.ts的内容
interface GeoQuery {
center(): number[];
radius(): number;
updateCriteria(criteria: GeoQueryUpdateCriteria);
on(eventType: EventType, callback: (key:string, location: number[], distance: number) => void): GeoCallbackRegistration;
cancel();
}
class GeoFire {
constructor(ref: any);
ref(): any;
set(key: string, loc: number[]): Promise<void>;
get(key: string): Promise<number[]>;
remove(key: string): Promise<void>;
query(criteria: GeoQueryCriteria): GeoQuery;
static distance(location1: number[], location2: number[]);
}
声明打字稿的正确方法如何?。简单的例子也不起作用
public pubVar:any;
constructor( public angularfireDatabase: AngularFireDatabase,
private geolocation: Geolocation) { }
ionViewDidLoad() {
this.pubVar = 'hii';
this.geolocation.getCurrentPosition().then((resp) =>
this.geoQuery= this.geoFire.query({
center: [resp.coords.latitude, resp.coords.longitude],
radius: 20 //kilometers
});
this.geoQuery.on("key_entered", function (key, location, distance) {
console.log('from geofire ' +location, ' key ' + key,distance);
console.log(this.pubVar);
}).catch((error) => {
console.log('Error getting location', error);
});
}
也回来了
Uncaught TypeError: Cannot read property 'pubVar' of undefined
关键字“this”未定义或绑定在回调内部,因此它将以未定义的形式返回。如果使用胖箭头表示法,使用key_entered事件,“this”将在回调范围内:
this.geolocation.getCurrentPosition().then((resp) =>
this.geoQuery= this.geoFire.query({
center: [resp.coords.latitude, resp.coords.longitude],
radius: 20 //kilometers
});
this.geoQuery.on("key_entered", (key, location, distance) => {
console.log('from geofire ' +location, ' key ' + key,distance);
this.angularfireDatabase.object('/products/'+key).subscribe((product) => {
this.products.push(product);
});
});
}).catch((error) => {
console.log('Error getting location', error);
});