首页 > 解决方案 > Angular Http请求未填充数据

问题描述

我在本地有以下 webapi 调用:

http://localhost:9091/api/vehicle/vehicles/GetAllVehicles

从我的组件中,我正在调用一个服务,该服务最终对上述 URL 进行 Http 调用。当我在我的 WebAPI 控制器上放置一个断点时,它被击中,我可以看到返回了响应。问题是,我的组件没有显示数据。我错过了什么:

Web API 响应:

[
  {
    "Make": "Ford",
    "Model": "ranger",
    "EngineCapacity": 3.2,
    "CylinderVariant": 4,
    "TopSpeed": 160,
    "Price": 610000,
    "ID": 3
  },
  {
    "Make": "Ford",
    "Model": "Mustang",
    "EngineCapacity": 8,
    "CylinderVariant": 8,
    "TopSpeed": 280,
    "Price": 950000,
    "ID": 4
  },
  {
    "Make": "Tata",
    "Model": "Tiago",
    "EngineCapacity": 1,
    "CylinderVariant": 2,
    "TopSpeed": 90,
    "Price": 110000,
    "ID": 5
  },
  {
    "Make": "Toyota",
    "Model": "Hilux",
    "EngineCapacity": 3,
    "CylinderVariant": 4,
    "TopSpeed": 160,
    "Price": 609999,
    "ID": 2
  },
  {
    "Make": "Volkswagon",
    "Model": "Polo",
    "EngineCapacity": 1.6,
    "CylinderVariant": 4,
    "TopSpeed": 200,
    "Price": 209999,
    "ID": 1
  }
]

fetchdata.component.html

<h1>Vehicle Inventory</h1>

<input placeholder="Search" [(ngModel)]="searchText" /> <input class="btn btn-default" type="button" (click)="search()" value="Search" />

<p *ngIf="!vehicles"><em>No data...</em></p>

<table class='table' *ngIf="vehicles">
    <thead>
        <tr>
            <th>Model</th>
            <th>Make</th>
            <th>Engine Capacity</th>
            <th>Cylinder Variant</th>
            <th>Top Speed</th>
            <th>Price R</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let vehicle of vehicles">
            <td>{{ vehicle.Make }}</td>
            <td>{{ vehicle.Model }}</td>
            <td>{{ vehicle.EngineCapacity }}</td>
            <td>{{ vehicle.CylinderVariant }}</td>
            <td>{{ vehicle.TopSpeed }}</td>
            <td>{{ vehicle.Price }}</td>
        </tr>
    </tbody>
</table>

fetchdata.component.ts

import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';
import { VehicleService } from '../../Services/VehicleService';
import { Vehicle } from '../../Models/Vehicle';

@Component({
    selector: 'fetchdata',
    templateUrl: './fetchdata.component.html',
    providers: [VehicleService]
})
export class FetchDataComponent {
    public vehicles: Vehicle[];
    public searchText: string = "";

    constructor(private vehicleService: VehicleService) { }

    ngOnInit(): void {
        this.vehicleService.GetAllVehicles()
            .then(response => this.vehicles = response);

        console.log(this.vehicles.entries.length);
    }

    search(searchText: string): void {
        this.vehicleService.SearchVehiclesByMakeAndModel(searchText)
            .then(response => this.vehicles = response);
    }
}

车辆服务

import { Http } from '@angular/http';
import { Injectable, Inject } from '@angular/core';
import { Vehicle } from '../Models/Vehicle';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { DecimalPipe } from '@angular/common';

@Injectable()
export class VehicleService {

    private readonly VehicleBaseEndpoint = "http://localhost:9091/api/vehicle";

    constructor(private httpClient: Http) { }

    public AddVehicle(vehicle: Vehicle): Promise<Vehicle> {
        var route = this.VehicleBaseEndpoint + "/vehicles/add";
        //do some manipulation: CylinderCapactiy = Enginesize / CylinderVariant
        //vehicle.CylinderCapacity = vehicle.EngineCapacity / vehicle.CylinderVariant;
        return this.httpClient.post(route, JSON.stringify(vehicle))
            .toPromise()
            .then(response => response.json().data as Vehicle)
            .catch(this.handleError);
    }

    public GetAllVehicles(): Promise<Vehicle[]> {
        var route = this.VehicleBaseEndpoint + "/vehicles/GetAllVehicles";
        return this.DoRequest(route);
    }

    private DoRequest(route: string): Promise<Vehicle[]> {
        return this.httpClient.get(route)
            .toPromise()
            .then(response => response.json().data as Vehicle[])
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); 
        return Promise.reject(error.message || error);
    }
}

车辆

export class Vehicle {

    constructor() { }

    public Make: string;
    public Model: string;
    public EngineCapacity: any;
    public CylinderVariant: any;
    public TopSpeed: number;
    public Price: any;
}

我在这里想念什么?为什么结果没有显示在我的组件中?

标签: angularvisual-studio-2017typescript2.0angular-httpclient

解决方案


*ngIf在一个boolean值上工作,你需要传递一个条件,

更改vehiclesvehicles.length > 0

<p *ngIf="vehicles.length == 0"><em>No data...</em></p>

<table class='table' *ngIf="vehicles.length > 0">

推荐阅读