gpt4 book ai didi

json - 需要帮助解析 JSON 响应 Angular 4

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:24:51 27 4
gpt4 key购买 nike

我正在研究 Angular 4 和 PHP、Mysql。我从服务器的响应是

[{"transportation_pf":"1"},[{"destination":"Swarget"}],
{"transportation_pf":"5"},[{"destination":"Swarget"},
{"destination":"Dombivli"}]]

总线服务和组件是

import { Injectable } from '@angular/core';
import {Bus } from './bus';
import {Headers,Http } from '@angular/http';
import {Observable} from'rxjs/Observable';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class BusService {
private busUrl='http://localhost/MycityDB/bus.php';
constructor(private http:Http) { }

getPlatforms(){

return this.http.get(this.busUrl).map(
(res)=>res.json()
);

}

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

}

总线组件是

import { Component, OnInit } from '@angular/core';
import { Bus } from './bus';
import {BusService } from './bus.service';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
import 'rxjs/add/operator/map';


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

busData: Bus[];
loadedCharacter: {};
private busUrl='http://localhost/MycityDB/bus.php';
constructor(private http: Http,private busservice: BusService) { }

ngOnInit() {
this.busservice.getPlatforms().subscribe(
(data)=>this.busData=data
);

}

}

总线组件html是

<p *ngFor="let bus of busData">
Bus works ! {{bus.destination}}
</p>

总线类如下

export class Bus {
transportation_pf : string;
destination: string[];
}

Html 输出只显示我不知道代码哪里出错了。

# Bus works ! #
# Bus works ! #
# Bus works ! #
# Bus works ! #

有人可以帮忙吗?我很困惑。

最佳答案

尝试添加 *ngIf="busData"

<div *ngIf="busData">
<p *ngFor="let bus of busData">
Bus works ! {{bus.destination}}
</p>
</div>

或异步管道

<p *ngFor="let bus of busData | async">

这是 Observable 的。

必须在服务中添加

import 'rxjs/add/operator/map';

关于json - 需要帮助解析 JSON 响应 Angular 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44733161/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com