這與Typescript getCurrent location and pass to backend to get the result and pass to Material Table data source幾乎是相同的問題,但是這個問題我只得到了如何獲取當前位置並傳遞到後端的答案,由libertyernie的答案作品。所以我問這一個...使用角度材質2表根據用戶當前位置顯示來自後端的結果
這是問題: 我想使用Angular Material 2表來顯示餐廳(這是來自我的春季啓動後端)列表。根據他們在github上給出的教程,數據源必須是可觀察的,這是有道理的,因爲您可以對列進行排序或過濾數據。但是,當我嘗試與當前位置集成時,我不知道如何使其工作...
該方案與我鏈接的問題相同,即嘗試獲取用戶的當前位置,並且一旦它獲得(例如,lat=123
和lon=123
),我會將這兩個參數傳遞到我的後端地址:http://localhost:8080/api/search/location?lat=123&lon=123
,這將返回一個餐廳列表,並且我需要以某種方式更改爲Observable,以使ExampleDataSource
中的connect()
函數有效。
下面的代碼是我已經嘗試過的,但是我失敗了,數據源沒有任何迴應。
import { Component, OnInit } from '@angular/core';
import { Http, Response, URLSearchParams } from '@angular/http';
import { DataSource } from '@angular/cdk';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';
import { Restaurant } from '../restaurant/restaurant';
import { Category } from '../category/category';
import { RestaurantService } from '../restaurant/restaurant.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
displayedColumns = ['Id', 'Name', 'Category', 'Address', 'City'];
exampleDatabase: ExampleHttpDatabase | null;
dataSource: ExampleDataSource | null;
location: CurrentLocation | null;
lat: any;
lon: any;
result: Promise<any>;
constructor(http: Http) {
this.exampleDatabase = new ExampleHttpDatabase(http);
this.dataSource = new ExampleDataSource(this.exampleDatabase);
this.location = new CurrentLocation(http);
}
ngOnInit() {
this.result = this.location.getCurrentLocation(this.lat, this.lon);
this.result.then(function(result){
console.log(result._body);
})
console.log(this.lat, this.lon);
this.dataSource.connect();
}
}
export class ExampleHttpDatabase {
private restaurantUrl = 'api/restaurant'; // URL to web API
getRestaurants(): Observable<Restaurant[]> {
var result = this.http.get(this.restaurantUrl)
.map(this.extractData);
result.toPromise();
return result;
}
extractData(result: Response): Restaurant[] {
return result.json().map(restaurant => {
return {
id: restaurant.id,
name: restaurant.restaurant_name,
category: restaurant.category.map(c => c.categoryName).join(','),
address: restaurant.address.address,
city: restaurant.address.city.city_name
}
});
}
constructor(private http: Http) { }
}
export class CurrentLocation {
constructor(private http: Http) { }
private lat: any;
private lon: any;
private params = new URLSearchParams();
private url = 'api/search/location';
getPosition =() => {
var latitude, longitude;
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition((position) => {
resolve(position.coords);
}, (err) => {
reject(err);
});
})
}
async getCurrentLocation(lat, lon): Promise<any> {
let coords = await this.getPosition();
lat = this.lat = coords['latitude'];
lon = this.lon = coords['longitude'];
this.params.set('lat', this.lat);
this.params.set('lon', this.lon);
var result = this.http.get(this.url, { search: this.params });
return await result.toPromise();
}
}
export class ExampleDataSource extends DataSource<Restaurant> {
constructor(private _exampleDatabase: ExampleHttpDatabase) {
super();
}
/** Connect function called by the table to retrieve one stream containing the data to render. */
connect(): Observable<Restaurant[]> {
return this._exampleDatabase.getRestaurants();
}
disconnect() { }
}
的完整代碼也Github上:https://github.com/zhengye1/Eatr/tree/dev
不知道你是什麼在'Observable'中完全改變了,但是如果你正在尋找一個例子來設置'connect()'從API檢索數據,你可以檢查這個[answer](https://stackoverflow.com/a/45394504/5556177)和[plunker](https://plnkr.co/edit/ivvQqO5dXB92IXN8zOFv?p=preview)。 – Nehal
@Nehal感謝您的評論,讓我更容易提出這個問題。我想在用戶到達主頁時獲取用戶的當前位置,一旦我的前端獲得經緯度,將其發送到後端並返回用戶附近的餐館列表,以便我的前端可以選擇結果返回並放入物料表並顯示給用戶。我該如何解決這個問題? –