angular - 传单使功能同步
问题描述
我试图在另一个函数中调用 setMarker() 函数。但是标记没有设置。我不知道为什么,但可能是因为 setMarker() 函数是异步的,因为 Promise。
获取城市()
getCities(rawData) {
for (const index in rawData['data']) {
if (rawData.meta.c0Name == 'city') {
const city: string = rawData['data'][index]['c0'];
if (city != undefined) {
this.setMarker(city);
}
}
}
设置标记()
setMarker(location: string) {
const provider = new OpenStreetMapProvider();
const query_promise = provider.search({
query: location,
});
query_promise.then(
(value) => {
// Success!
const x_coor = value[0].x;
const y_coor = value[0].y;
const label = value[0].label;
this.citiesLayer = [
L.marker([y_coor, x_coor])
.bindPopup('<b>Found location</b><br>' + label)
.addTo(this.citiesLayerGroup),
];
},
(reason) => {
console.log(reason); // Error!
}
);
}
我从 webDataRocksComponent 获得的 rawData
getDataForMap() {
this.child.webDataRocks.getData(
{},
(rawData) => {
this.mapComponent.getCities(rawData);
},
(rawData) => {
this.mapComponent.getCities(rawData);
}
);
}
解决方案
您的代码看起来不错,请确保已将this.citiesLayerGroup
其初始化并添加到地图中:
this.citiesLayerGroup = L.featureGroup().addTo(map); // or L.layerGroup
另外我认为您想将新标记推送到数组中而不是覆盖它:
if(!this.citiesLayer){
this.citiesLayer = []
}
this.citiesLayer.push(L.marker([y_coor, x_coor])
.bindPopup('<b>Found location</b><br>' + label)
.addTo(this.citiesLayerGroup),
);
如果它仍然不起作用,请检查是否this
是正确的上下文:
var that = this;
query_promise.then(
(value) => {
// Success!
const x_coor = value[0].x;
const y_coor = value[0].y;
const label = value[0].label;
console.log(this);
console.log(that)
that.citiesLayer = [ // changed to that
L.marker([y_coor, x_coor])
.bindPopup('<b>Found location</b><br>' + label)
.addTo(that.citiesLayerGroup), // changed to that
];
},
(reason) => {
console.log(reason); // Error!
}
);
推荐阅读
- c++ - 展开可变参数模板结构
- angularjs - 具有不同保存选项的 Angular MaterialJS 对话框表单
- php - 如何在不使用 markdown 的情况下将纯文本版本添加到 Laravel 电子邮件
- smtp - Msmtprc SMTP 与 Office365
- python - pyswagger 中的解析错误:ValueError: Can't resolve type from:(String, )
- c - C中的指针及其值
- java - Java8使用方法参考按2个字段排序
- visual-studio-code - 循环浏览 VSCode 活动栏图标
- html - 在 Firefox 中显示表格布局损坏
- php - 如何修复 JSON_ERROR_UTF8