使用Angular Material 2表时的奇怪行为(Angular 2 / Spring Boot后端)

时间:2017-08-21 13:03:41

标签: javascript angularjs angular-material2

继续Using angular material 2 table to display the result from backend based on user's current location

此代码的目的是当用户进入网站时,它会尝试询问用户当前位置。一旦我的前端获得当前的lat / lon,它将传递到后端以根据用户的位置获取最近的餐馆,并使用角度材料表来显示它。但是当我在Chrome上测试时,我得到了奇怪的行为,主页第一次不会立即显示结果,尝试刷新,不起作用,唯一的方法是让它工作是切换另一个标签,然后回到这个,它将在角度材料表中显示结果。

以下是home.component.ts

的代码
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 'rxjs/add/observable/frompromise';
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'];
  dataSource: ExampleDataSource | null;

  constructor(http: Http) {
    //this.exampleDatabase = new ExampleHttpDatabase(http, this.location);
    this.dataSource = new ExampleDataSource(http);

  }

  ngOnInit() {
    this.dataSource.connect();
  }
}

export class ExampleDataSource extends DataSource<Restaurant> {
  private url = 'api/search/location';
  private params = new URLSearchParams();
  private lat;
  private lon;
  constructor(private http: Http) {
    super();
  }

  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect(): Observable<Restaurant[]> {
    // var location;
    // if (navigator.geolocation){
    //   var options = {timeout: 60000};
    //   location = navigator.geolocation.getCurrentPosition((position)=>{
    //     return position;
    //   },(err) =>{
    //     console.log("Error")
    //   }, options);
    // }
    // console.log("Locations: " + location);
    var result = this.getCurrentLocation().then((res) => 
    {
      return res;
    });
    return Observable.fromPromise(result);
  }


  disconnect() { }
  getPosition = () => {
    var latitude, longitude;
    return new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition((position) => {
        resolve(position.coords);
      }, (err) => {
        reject(err);
      });
    })
  }
  async getCurrentLocation(): Promise<Restaurant[]> {
    let coords = await this.getPosition();
    this.lat = coords['latitude'];
    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 }).map(this.extractData);
    return await 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(','),
        address: restaurant.address.address,
        city: restaurant.address.city.cityName
      }
    });
  }
}

我不知道我做错了什么..有人能帮帮我吗?有关完整代码,请参阅https://github.com/zhengye1/Eatr/tree/dev

1 个答案:

答案 0 :(得分:0)

终于解决了......

我需要做的只是将HomeComponent类上的ngOnInit更改为以下

async ngOnInit() {
    await this.dataSource.connect();
}

它有效..不知道为什么......