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

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

问题描述

继续此代码的目的是当用户进入站点时,它将尝试询问用户当前位置.一旦我的前端获得当前的经度/纬度,它将根据用户的位置并使用角度材质表将其传递到后端以获取最近的餐厅.但是,当我在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天全站免登陆