Angularjs 4 HTTP获取对json文件的请求

时间:2017-06-02 09:41:33

标签: angularjs-http

我有下面的问题,我无法从json加载数据。 我尝试做的是访问给定的文件地址并拼写数据,但有些东西没有加载我试过而没有异步

driver-list.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/observable/throw';

import 'rxjs/add/operator/do';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';


@Injectable()
export class DriversListService {

  private baseUrl: string = 'http://ergast.com/api/f1/2016/driverStandings.json';
  constructor(private http : Http){}
  data  
  getDriver() {
    return this.http.get(this.baseUrl)
    .map(res => this.data = res.json())
  }
}

驱动一览page.component.ts

import { Component, OnInit } from '@angular/core';
import { DriversListService } from '../drivers-list-page/drivers-list.service'

@Component({
  selector: 'app-drivers-list-page',
  templateUrl: './drivers-list-page.component.html',
  styleUrls: ['./drivers-list-page.component.sass']
})
export class DriversListPageComponent implements OnInit {

  drivers = []
    constructor(private driverListServices: DriversListService) {}
    ngOnInit(){
      this.driverListServices.getDriver().subscribe(resDriverData=>this.drivers=resDriverData)
    }
}

驱动一览page.component.html

WORK
    <ul class="items">
       <li *ngFor="let driver of drivers | async">
          <span>{{driver}}</span>
       </li>
    </ul>

enter image description here

1 个答案:

答案 0 :(得分:0)

检查控制台日志,了解有关错误的更多信息... 那么我们可以帮到你

或尝试......

    import { Component, OnInit, Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { environment } from '../../environments/environment';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-searcher',
  templateUrl: './searcher.component.html',
  styleUrls: ['./searcher.component.css']
})
@Injectable()
export class SearcherComponent implements OnInit {

  // Pixabay API Key
  private key:string = environment.PIXABAY_API_Key;
  // API Url
  url:string;
  // Array of result
  images:any[];
  // Result per page
  per_page:number;
  // User query
  query:string;

  constructor(private result: Http) { 
  }

  ngOnInit() {
  }

  // Get http result
  letSearch(query){
    this.url = "https://pixabay.com/api/?key=" + this.key + "&q=" + query;
    return this.result.get(this.url).map(res => res.json()).subscribe(
      data => console.log(data),
      error => console.log(error),
      () => console.log("Fine !")
    );
  }

}