订阅完成后如何调用函数

时间:2021-05-26 09:23:25

标签: angular typescript subscribe

我有这个服务调用,我订阅了一个 Observable 并将响应分配给一个属性。我的目的是在服务调用完成后调用另一个将使用此属性的函数。最好的方法是什么?

export class MapComponent implements AfterViewInit, OnInit {
@ViewChild("mapContainer", { static: false }) gmap: ElementRef;
map: google.maps.Map;
markers = [];

 constructor(private userService : UserService) {}

 ngOnInit() {
   console.log("Point 1 ##################");
   this.userService.getUserMarkers().subscribe(markers => {
      this.markers = markers;
      console.log("Point 2 ##################");
   });
 }

 ngAfterViewInit(): void {
   console.log("Point 3 ##################");
   this.mapInitializer();
 }

 mapInitializer(): void {
   console.log("Point 4 ##################");
   // function where to use the markers
 }

现在发生的顺序是, 点 1 -> 点 3 -> 点 4 -> 点 2

最好的方法是什么 点 1 -> 点 2 -> 点 3 -> 点 4

1 个答案:

答案 0 :(得分:1)

您不能按照您想要的方式执行此操作,因为 Angular Lifecycle 将照常执行。但我想你需要这样的东西:

 ngOnInit() {
   console.log("Point 1 ##################");
   this.userService.getUserMarkers().subscribe(markers => {
      this.markers = markers;
      console.log("Point 2 ##################");
      this.mapInitializer();
   });
 }

 ngAfterViewInit(): void {
   console.log("Point 3 ##################");
 }

 mapInitializer(): void {
   console.log("Point 4 ##################");
   // function where to use the markers
 }

所以,新的序列将是:Point 1 -> Point 3 -> Point 2 -> Point 4

相关问题