首页 > 解决方案 > 在订阅标注之外使用变量

问题描述

所以我正在开发一个角度应用程序,我想访问一个包含纬度和经度的节点列表以放入地图。我获取对象节点的方式是通过一个服务,该服务基本上从我的 mongoDB 数据库中获取所有对象

retrieveNodes() {

this.nodeService.getAll()
  .subscribe(
    data => {
      this.nodes = data;
      console.log(data);
    },
    error => {
      console.log(error);
    });
    }

变量 this.nodes 被声明为 nodes:any; 在一开始

然后我有这个我使用我得到的信息来放置坐标

writeNodes() {
var summit = L.marker([this.nodes[0].latitude,this.nodes[0].longitude], {
    icon: L.icon({
      iconSize: [25, 41],
      iconAnchor: [13, 41],
      iconUrl: 'leaflet/marker-icon.png',
      shadowUrl: 'leaflet/marker-shadow.png'
    })
  });

  return summit;
}

当我在订阅中使用 console.log(nodes[0].latitude) 时,我得到了正确的数字,但是当我在第二个示例中使用 console.log 时,我得到了未定义。

PS:我在 onInit() 方法中运行 retrieveNodes(),这就是我填充变量 this.nodes 的方式。另外,我测试了将retrieveNodes() 作为一个返回列表并在writeNodes() 中调用的函数,但我无法填充列表。仅当我在数据内=>{

谢谢您的帮助

标签: javascriptangular

解决方案


您已经在使用返回 observable 的服务。所以使用该服务来维护节点列表。通过使用服务构造函数检索所有节点并将 Observable 存储在服务本身的实例变量中来做到这一点。

这为节点创建了一个单一的真实来源,并允许您只需要在 OnInit() 方法中“writeNodes”。

这是 AppComponent 的样子:

export class AppComponent implements OnInit {
  name = 'Angular 5';
  nodeService: NodeService;
  summit;

  constructor(nodeService: NodeService) {
    this.nodeService = nodeService;
  }

  ngOnInit(): void {
    this.nodeService.nodes.subscribe((nodes) => {
      this.summit = nodes[0];
    });
  }
}

这就是服务的样子(节点被模拟)

interface Node { latitude: number, longitude:number};

@Injectable()
export class NodeService {

  nodes: Observable<Node[]>;

  constructor() {
    this.nodes = this.getAllNodes();
  }

  getAllNodes(): Observable<Node[]> {
    return of([{latitude:1,longitude:2},{latitude:3,longitude:4}]);
  }
}

最后,这是一个带有这个工作示例的 StackBlitz:

https://stackblitz.com/edit/angular-hauax8?file=app/services/nodeService.ts


推荐阅读