使用 Angular Material 2 表时的奇怪行为(Angular 2/Spring Boot 后端) [英] Weird behavior when using Angular Material 2 table (Angular 2/Spring Boot backend)

查看:20
本文介绍了使用 Angular Material 2 表时的奇怪行为(Angular 2/Spring Boot 后端)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

继续使用angular material 2 table根据用户当前位置显示来自后端的结果

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

My purpose for this code is when user enter the site, it will try to ask user the current location. Once my front end get current lat/lon, it will pass to backend to get the nearest restaurant based on user's location, and using angular material table to display it. But when I testing on Chrome, I got weird behavior, the home page will not display the result immediately on the first time, try refresh, doesn't work, the only way make it works is switch another tab, and back to this one, it will display the result in angular material table.

这里是 home.component.ts 的代码

Here is the code for 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

I don't know what I did wrong.. can someone help me? For the full code, please see https://github.com/zhengye1/Eatr/tree/dev

推荐答案

终于解决了....

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

All I need to do just change ngOnInit on HomeComponent class to following

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

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

and it works.. don't know why...

这篇关于使用 Angular Material 2 表时的奇怪行为(Angular 2/Spring Boot 后端)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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