使用角度材质2表格根据用户当前位置显示后端结果 [英] Using angular material 2 table to display the result from backend based on user's current location

查看:151
本文介绍了使用角度材质2表格根据用户当前位置显示后端结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与 Typescript getCurrent位置并传递到后端以获取结果并传递到Material Table数据源,但是这个问题我只得到了如何获取当前位置并传递给后端的答案,以及哪些它由libertyernie的回答起作用。因此,我问这一个...

这是问题:
我想使用Angular Material 2表来显示餐厅列表(它来了从我的spring-boot后端)。根据他们在github上给出的教程,数据源必须是可观察的,这是有道理的,因为您可以对列进行排序或过滤数据。但是,当我尝试与当前位置集成时,我不知道如何使其工作......



该场景与我链接的问题相同,即尝试获取用户的当前位置,一旦获得位置(例如, lat = 123 lon = 123 ),我会将这两个参数传递到我的后端地址: http:// localhost:8080 / api / search / location?lat = 123& lon = 123 将返回一个餐厅列表,我需要以某种方式更改为Observable,以便中的 connect()函数ExampleDataSource



下面的代码是我已经尝试过的,但是我失败了,数据源没有任何回应。

 从'@ angular / core'导入{Component,OnInit}; 
从'@ angular / http'导入{Http,Response,URLSearchParams};
从'@ angular / cdk'导入{DataSource};
从'rxjs / BehaviorSubject'导入{BehaviorSubject};
从'rxjs / Observable'导入{Observable};
导入'rxjs / add / operator / startWith';
导入'rxjs / add / observable / merge';
导入'rxjs / add / operator / map';
从'../restaurant/restaurant'导入{Restaurant};
从'../category/category'导入{Category};
从'../restaurant/restaurant.service'中导入{RestaurantService};

$ b @Component({
selector:'app-home',
templateUrl:'./home.component.html',
styleUrls: ['./home.component.css']
})
导出类HomeComponent实现OnInit {
displayedColumns = ['Id','Name','Category','Address', '市'];
exampleDatabase:ExampleHttpDatabase |空值;
dataSource:ExampleDataSource |空值;
位置:CurrentLocation |空值;
lat:any;
lon:any;
结果:Promise< any>;

构造函数(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'; //网络API的URL
getRestaurants():可观察< Restaurant []> {
var result = this.http.get(this.restaurantUrl)
.map(this.extractData);
result.toPromise();
返回结果;


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(','),
地址:restaurant.address.address,
city:restaurant.address.city.city_name
}
});
}
构造函数(private http:Http){}
}

导出类CurrentLocation {
构造函数(private http:Http){}
私人拉特:任何;
private lon:any;
private params = new URLSearchParams();
private url ='api / search / location';


getPosition =()=> {
var纬度,经度;
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});
返回await result.toPromise();
}
}

导出类ExampleDataSource扩展了DataSource< Restaurant> {
构造函数(private _exampleDatabase:ExampleHttpDatabase){
super();
}

/ **连接表中的函数以检索一个包含要呈现的数据的流。 * /
connect():Observable< Restaurant []> {
return this._exampleDatabase.getRestaurants();


disconnect(){}
}

完整的代码也在Github: https://github.com/zhengye1/Eatr/tree/ dev

解决方案

最后,我可以将信息显示在主页上,但会发生奇怪的行为,请参阅这个链接:奇怪的行为时使用Angular Material 2表(Angular 2 / Spring Boot后端)

This is the almost same question as Typescript getCurrent location and pass to backend to get the result and pass to Material Table data source, but this question I only got the answer for how to get the current location and pass to backend and which it works by libertyernie's answer. Therefore I ask this one...

Here is the issue: I want to use Angular Material 2 table to display the list of restaurant (which is come from my spring-boot backend). And based on the tutorial they gave on github, the data source must be observable, which is make sense, because you can sort column or filter the data something like that. But when I try to integrate with current location, I don't know how to make it work...

The scenario is same as the question I linked, which is try to get user's current location, and once it got the location (for example ,lat=123 and lon=123), I will pass this two parameters into my backend address: http://localhost:8080/api/search/location?lat=123&lon=123, and this will return a list of Restaurant, and I need to somehow change to Observable so that the connect() function in ExampleDataSource works.

The code below is what I already tried, but I am failed, the datasource get nothing back.

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() { }
}

Full code also in Github: https://github.com/zhengye1/Eatr/tree/dev

解决方案

Finally I can get the information to display to the home page, but weird behavior happens, please see this link : Weird behavior when using Angular Material 2 table (Angular 2/Spring Boot backend)

这篇关于使用角度材质2表格根据用户当前位置显示后端结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆