【发布时间】:2019-05-18 04:48:14
【问题描述】:
我正在尝试从 api 获取数据,但无法打印应用程序中的值。没有正确读取 json。不知道我做错了什么......任何帮助都会有所帮助。我需要能够在 json 中向下解析以获取strat_name
这是我的代码
home.ts:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { RestApiProvider } from '../../providers/restapi/restapi';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
names: string[];
errorMessage: string;
descending: boolean = false;
order: number;
column: string = 'name';
constructor(public navCtrl: NavController, public rest: RestApiProvider) { }
ionViewDidLoad() {
this.getNames();
}
getNames() {
this.rest.getNames()
.subscribe(
names => this.names = names,
error => this.errorMessage = <any>error
);
}
sort() {
this.descending = !this.descending;
this.order = this.descending ? 1 : -1;
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>
Name List
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-searchbar [(ngModel)]="terms"></ion-searchbar>
<button ion-button type="button" (click)="sort()">Sort</button>
<h1>{{names | json}}</h1>
<ion-item *ngFor="let c of names | search : terms | sort: {property: column, order: order}">
<h2>{{c.strat_name}}</h2>
</ion-item>
</ion-content>
restapi:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { map, catchError } from 'rxjs/operators';
@Injectable()
export class RestApiProvider {
private apiUrl = 'https://macrostrat.org/api/v2/defs/strat_names?all';
constructor(public http: HttpClient) {
console.log(this.apiUrl);
}
getNames(): Observable<string[]> {
return this.http.get(this.apiUrl).pipe(
map(this.extractData),
catchError(this.handleError)
);
}
private extractData(res: Response) {
let body = res;
return body || {};
}
private handleError (error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const err = error || '';
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
不确定我做错了什么......任何帮助都会有所帮助。我需要能够在 json 中解析以获取strat_names。
【问题讨论】:
-
嗨!你有什么错误吗?你能在home.ts中api响应后记录服务器的响应和名称的内容吗?
-
请您在您的 html 中添加这个(在排序按钮之后)并分享结果
{{names | json}} -
这是正确的吗? {{names | json}} 所以当我这样做时,我得到 items.filer 不是函数@RezaRahmati
-
json 管道只是在您的 html 中将您的对象显示为 json,因此不会导致该问题,但这也意味着您的代码中存在问题,因此请删除 @987654327 @来自你的
ion-item -
@RezaRahmati 现在我在尝试区分“{Object Object}”时遇到错误。只允许使用数组和可迭代对象
标签: json typescript api ionic3 angular5