代码之家  ›  专栏  ›  技术社区  ›  Matt

显示从api获取的数据

  •  0
  • Matt  · 技术社区  · 6 年前

    我能够记录请求数据并将它们记录到控制台中。

    enter image description here

    这是我的服务组件:

    import {Injectable} from '@angular/core';
    import {HttpClient } from '@angular/common/http';
    
    
    
    @Injectable({
      providedIn: 'root'
    })
    export class EarthquakeService {
    
    
      constructor(private http: HttpClient) {}
    
      getEarthquakes(){
        return this.http.get('http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson');
      }
    
    
    }

    import { Component, OnInit } from '@angular/core';
    
    import {EarthquakeService} from '../../services/earthquake/earthquake.service';
    
    
    
    @Component({
      selector: 'app-earthquake-page',
      templateUrl: './earthquake-page.component.html',
      styleUrls: ['./earthquake-page.component.scss']
    })
    export class EarthquakePageComponent implements OnInit {
    
      earthquakes: string[];
      eathqaukeTitle: string;
    
      constructor(private earthquakeService: EarthquakeService) {
    
      }
    
      ngOnInit() {
        this.getEarthqaukes();
    
    
      }
    
      getEarthqaukes(){
        this.earthquakeService.getEarthquakes().subscribe(
          (response) => console.log(response),
          (error) => console.log(error)
        );
      }
    
    }

    现在我不知道如何将这些数据保存到数组中并在页面上显示它们。

    2 回复  |  直到 6 年前
        1
  •  2
  •   devDan    6 年前

    我想你在做你的衣服时少了一些零件 http 请求获取数据,请尝试以下操作。请求应该与下面的内容类似,不能从图片中很好地计算出JSON。

    请求

    import { map } from 'rxjs/operators';
    import { Observable } from 'rxjs';
    
    
    public getEarthquakes(): Observable<any>{
        return this.http.get('http://earthquake.usgs.gov/
          earthquakes/feed/v1.0/summary/all_hour.geojson').pipe(map(data => data));
    }
    
    //only on two lines for SO readability 
    

    组成部分

     public earthQuakes = [];    
    
      getEarthqaukes(){
      this.earthquakeService.getEarthquakes().subscribe(
        (response) => {
           console.log(response)
           this.earthQuakes = response.features; // whichever bit you are looking for.
      },
      (error) => console.log(error)
      );
    }
    

    HTML格式

    <div *ngFor="let shake of earthQuakes">
      <span>{{shake}}</span>
    </div>
    

    Documentation on using *ngFor

    这并不像前面提到的那样完美,不能很好地看到完整的JSON,但这肯定足以填补空白。正如 the head rush 你应该看看这个 tutorial 确保你在学习的过程中了解自己在做什么。