所以我有這個 angular 程式,到目前為止我從用戶那里接收一個郵政編碼,并在單擊按鈕時將該輸入發送到一個函式,在那里它被發送到一個 api 以轉換為緯度和經度坐標。見下文:
主頁.component.html
<div class="center" style="margin-top:50px;">
<label for="ZipCode"><b>Zip Code</b></label>
</div>
<div class="center">
<input name="zipcode" #zipcode id="zipcode" type="text" placeholder="Enter Zip Code" maxlength="5">
</div>
<div class="center" style="margin-top:100px;">
<button class="button button1" (click)="getCoords(zipcode.value)" ><b>Retrieve Data</b></button>
</div>
顯然,這只是代碼的一個片段,但對于顯示目的來說已經足夠了。接下來是帶有 api 的函式,然后它將視圖轉移到站組件/頁面:
主頁.component.ts
export class HomeComponent implements OnInit {
constructor(
private router: Router
){}
ngOnInit(): void {
}
getCoords(val: any){
var url = "http://www.mapquestapi.com/geocoding/v1/address?key=MYKEY&location=" val;
fetch(url)
.then((res) => res.json())
.then((data) => {
var lat = data.results[0].locations[0].displayLatLng.lat;
var long = data.results[0].locations[0].displayLatLng.lng;
this.router.navigate(["/stations"])
})
}
}
station.component.ts - 因為你在這里什么也看不到,因為我不知道該怎么做
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-stations',
templateUrl: './stations.component.html'
})
export class StationsComponent implements OnInit {
ngOnInit(): void {
}
}
現在這一切正常。我已經在控制臺日志中測驗了 lat 和 long 變數,它回傳了 lat 和 long 就好了。我的問題是我需要將經緯度值發送到另一個組件/頁面以用于計算。我不會撒謊說我已經在互聯網上搜索并試圖找到一種方法來做到這一點,但顯然在角度上這樣做并不容易。有人對將 lat 和 long 值傳遞給另一個組件/頁面有任何想法嗎?
uj5u.com熱心網友回復:
您可以使用像波紋管代碼這樣的查詢引數處理↓
getCoords(val: any){
var url = "http://www.mapquestapi.com/geocoding/v1/address?key=MYKEY&location=" val;
fetch(url)
.then((res) => res.json())
.then((data) => {
var lat = data.results[0].locations[0].displayLatLng.lat;
var long = data.results[0].locations[0].displayLatLng.lng;
this.router.navigate(["/stations"], {queryParams :{ dataLat : lat, dataLong : long}} )
})
}
在您的stations.component.ts 中,您可以使用 ActivatedRoute 來獲取資料:
import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-stations',
templateUrl: './stations.component.html'
})
export class StationsComponent implements OnInit {
getLat:any;
getLong:any;
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
this.route.queryParams.subscribe(params => {
this.getLat = params.dataLat;
this.getLong = params.dataLong;
console.log(params);
});
}
}
你可以在這里了解更多關于引導路由器和這里的資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/362675.html
上一篇:將專案添加到陣列后重置輸入欄位
