无法将http请求转换为可观察数组Angular 2

时间:2016-09-08 17:42:05

标签: json api angular reactive-programming

我一直关注Tour of Heroes chapter on http calls,并尝试使用不同的API实现类似的功能。 但是,我收到以下错误:

无法找到不同的支持对象' [object Object]'类型'邦德街1'。 NgFor仅支持绑定到诸如Arrays之类的Iterables。

有关原因的任何线索?

我的服务如下所示,当我在console.log结果

时工作
  search(stationNumber: number): Observable<BikeStand[]> {
    return this.http.get(`APIURL${stationNumber}`)
      .map((b: Response) => {
        console.log(b.json() as BikeStand[])
        return b.json() as BikeStand[];
      });
  }

我的组件如下所示

export class BikestandSearchComponent implements OnInit {

  bikestands: Observable<BikeStand[]>;
  private searchTerms = new Subject<number>();

  constructor(private bikestandSearchService: BikestandSearchService) { }

  search(term: number): void {
    this.searchTerms.next(term);
  }

  ngOnInit(): void {
    this.bikestands = this.searchTerms
      .debounceTime(300)
      .distinctUntilChanged()
      .switchMap(term => term ? this.bikestandSearchService.search(term) : Observable.of<BikeStand[]>([]))
      .catch(error => {
        console.log(error);
        return Observable.of<BikeStand[]>([])
      })
  }

我的观点喜欢这个

<div id="search-component">
  <h4>Bikestand search</h4>
  <input #searchBox id="search-box" (keyup)="search(searchBox.value)" />
  <div *ngFor="let bikestand of bikestands | async">{{bikestand.name}}</div>
</div>

我对给定密钥的api如下所示

{
number: 1,
name: "Bond Street 1",
address: "Street",
position: {
lat: 55.340962,
lng: -6.3
},
banking: false,
bonus: false,
status: "OPEN",
contract_name: "City",
bike_stands: 29,
available_bike_stands: 19,
available_bikes: 10,
last_update: 1473356300000
}

2 个答案:

答案 0 :(得分:1)

如错误所述,您尝试使用object而不是*ngFor来迭代array。你正在使用/返回的api是一个对象。

检查console.log(b.json() as BikeStand[])是否返回具有data属性的对象。如果是真的那么

return b.json().data代替。

我们希望从对象中提取数组以进行迭代。

答案 1 :(得分:1)

看起来您的服务或HTTP请求实际上并没有发送数组,而是发送一个Object。例如,我运行了这段代码:

import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <p *ngFor="let bike of bikestand">{{bike.name}}</p>
    </div>
  `,
})
export class App {

  bikestand:any = {
    number: 1,
    name: "Bond Street 1",
    address: "Street",
    position: {
      lat: 55.340962,
      lng: -6.3
    },
    banking: false,
    bonus: false,
    status: "OPEN",
    contract_name: "City",
    bike_stands: 29,
    available_bike_stands: 19,
    available_bikes: 10,
    last_update: 1473356300000
  };

  constructor() {
    this.name = 'Angular2'
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}`

并得到了同样的错误。但是将自行车支架改为实际阵列(通过在其周围放置方括号),我得到了正确的结果。