我是Angular 5的新手,我读了几篇关于Angular 5上的Http调用的文章。我仍然有些疑惑。我想用API和JSON格式填充下拉列表,如下所示。
{
"data": [
{
"type": "bus"
},
{
"type": "truck"
},
{
"type": "car"
}
],
"_metadata": null
}
这就是我的尝试。
应用组件
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {VehicleService } from './vehicle.service'
import { Vehicle } from './vehicle';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
_postsArray: Vehicle[];
result=[];
constructor(private http: HttpClient,
private vehicleService : VehicleService
){}
ngOnInit():void{
this.vehicleService.getVehicleData()
.subscribe(
resultArray=> this._postsArray=resultArray,
)
}
}
车辆服务类
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Vehicle } from './vehicle';
import 'rxjs/add/operator/map';
import {Http,Response} from "@angular/http";
import "rxjs/Rx";
@Injectable()
export class VehicleService {
constructor(private http: HttpClient) { }
textUrl = "http://test.com/vehicles/types";
getTenantData(): Observable<Vehicle[]> {
return this.http.get(this.textUrl)
.map((response:Response)=>{
return<Vehicle[]>response.json();
})
}
}
我使用组件进行下拉,因此html看起来像这样
<label>City</label>
<ng-select [items]="_postsArray"
bindLabel="name"
bindValue="id"
>
</ng-select>
我收到错误,因为ERROR TypeError:response.json不是函数。在Stack中找到并回答不需要json并仅添加.map(res =&gt; res);那里但我得到语法错误。请帮我解决这个问题。