Я пытаюсь использовать переменную в другой функции для создания маркера карты с помощью angular. я получил данные, которые будут храниться в функции и отображаться на консоли в одной функции, однако при использовании данных в другой функции это не работает:
компонент.ts:
import { HttpClient } from '@angular/common/http';
import { Component, OnInit, AfterViewInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { DAFormFac } from 'src/app/models/daformfac.interface';
import { DaformfacserviceService } from 'src/app/service/daformfacservice.service';
declare const L: any;
import { MocMapService } from 'src/app/service/moc-map.service';
import { map as MapData } from 'rxjs';
@Component({
selector: 'app-daform-fac-view-full',
templateUrl: './daform-fac-view-full.component.html',
styleUrls: ['./daform-fac-view-full.component.css'],
})
export class DaformFacViewFullComponent implements OnInit {
daformfac: DAFormFac[] = [];
formID: string;
getparamformid: any;
daformfacs: any;
latitude: any;
longitude: any;
private map: L.Map;
constructor(
private daformfacservice: DaformfacserviceService,
private route: ActivatedRoute,
private mapService: MocMapService,
private http: HttpClient,
) {}
ngOnInit(): void {
console.info(
this.route.snapshot.paramMap.get('facviewid'),
' : ID of report'
);
this.getparamformid = this.route.snapshot.paramMap.get('facviewid');
this.daformfacservice
.getOneDAFacForm(this.getparamformid)
.subscribe((daFormFac: DAFormFac) => {
this.daformfacs = daFormFac;
console.info(daFormFac, 'response of form');
this.latitude = daFormFac['latitude'];
this.longitude = daFormFac['longitude'];
console.info(this.latitude, this.longitude, "cords")
});
let map = L.map('map').setView([10.536421, -61.311951], 8);
L.tileLayer(
'https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token = {accessToken}',
{
attribution:
'Map data © <a href = "https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href = "https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1,
accessToken:
'pk.eyJ1IjoiZGlsbG9uciIsImEiOiJjbDB6MGdlbW8xNnZuM2lqbmJnNWZkNzY0In0.cfAOIAy5foQsoUlHhpYSjQ',
}
).addTo(map);
var marker = L.marker([this.latitude, this.longitude]).addTo(map);
console.info(this.latitude, this.longitude, "in marker")
//10.1896062, -61.5282025
//this.latitude, this.longitude
}
}
Услуга:
getOneDAFacForm(id: string) {
return this.http.get<any>("http://localhost:3000/DAFacility/"+id)
.pipe(map((res:any)=>{
return res;
}))
}
Эта функция получает ввод данных и сохраняет 2 переменные широту и долготу:
this.daformfacservice
.getOneDAFacForm(this.getparamformid)
.subscribe((daFormFac: DAFormFac) => {
this.daformfacs = daFormFac;
console.info(daFormFac, 'response of form');
this.latitude = daFormFac['latitude'];
this.longitude = daFormFac['longitude'];
console.info(this.latitude, this.longitude, "cords")
});
и это приводит к
однако при попытке доступа к данным вне функции консоль пуста.
var marker = L.marker([this.latitude, this.longitude]).addTo(map);
console.info(this.latitude, this.longitude, "in marker")
Он не отображается и недоступен. что я должен делать?
Я не уверен, применимо ли это, я уже получил данные в переменные, но использовать их вне функции, но в том же компоненте
@ user18451207, не могли бы вы обновить весь класс вместо указанного выше. Может поможет решить.
Просто добавил весь component.ts и сервисную функцию. @АрункумарРамасами
Вы вызываете переменные this.latitude
и this.longitude
до того, как вызов API вернет данные. Пожалуйста, попробуйте ниже
this.daformfacservice
.getOneDAFacForm(this.getparamformid)
.subscribe((daFormFac: DAFormFac) => {
this.daformfacs = daFormFac;
console.info(daFormFac, 'response of form');
this.latitude = daFormFac['latitude'];
this.longitude = daFormFac['longitude'];
console.info(this.latitude, this.longitude, "cords")
addMarker(); // called marker for map position
});
Здесь я вызвал addMarker после успешного вызова API.
addMarker() {
var marker = L.marker([this.latitude, this.longitude]).addTo(map);
console.info(this.latitude, this.longitude, "in marker");
}
я добавляю addMarker() вне компонента, то есть export class DaformFacViewFullComponent implements OnInit {}
addMarker(){}
или внутри функции ngOnInit
вы можете добавить метод addMarker
в класс, а не в метод ngOnInit
.
Ваша функция getOneDAFacForm будет выполняться асинхронно, что означает, что вы пытаетесь получить доступ к переменным (this.latitude, this.longitude) до того, как она будет инициализирована.
Эта строка console.info(this.latitude, this.longitude, "in marker")
вне функции будет выполнена перед этими строками
this.latitude = daFormFac['latitude'];
this.longitude = daFormFac['longitude'];
Отвечает ли это на ваш вопрос? Как вернуть ответ на асинхронный вызов