您好我正在实施一个observable来获取我的技能api,我现在有一个问题,即映射所请求的数据。 我的数组在请求结束时保持为null,我认为我的问题在于extractData()。
这是我的服务:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Skill } from './skill';
@Injectable()
export class CatalogService {
private api = 'http://127.0.0.1:8000/api/';
constructor(private http: Http) {}
getSkill(): Observable<Skill[]> {
return this.http.get(this.api + "skill")
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || {};
}
private handleError(error: Response | any) {
// In a real world app, you might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
这是我的.ts,我称之为服务
import { Component, OnInit } from '@angular/core';
import {CatalogService} from './catalog.service';
import {Skill} from './skill';
@Component({
selector: 'app-catalog',
templateUrl: './catalog.component.html',
styleUrls: ['./catalog.component.css']
})
export class CatalogComponent implements OnInit {
skills:Skill[];
errorMessage:string;
mode = 'Observable';
constructor(private catalogService: CatalogService) { }
ngOnInit() {
this.getSkill();
}
getSkill() {
this.catalogService.getSkill()
.subscribe(
skills => this.skills =skills,
error => this.errorMessage = <any>error);
}
}
这是我的api技能返回的结果:
[
{
"id": 2,
"experience": "null",
"typeskill": 1,
"profile": 2
},
{
"id": 3,
"experience": "null",
"typeskill": 1,
"profile": 3
}
]
我很感谢帮助解决这个问题。
答案 0 :(得分:0)
我解决了将我的服务中的函数getSkill()更改为:
getSkill(): Observable<Response> {
return this.http.get(this.api + "skill")
.catch(this.handleError);
}
.ts文件到此:
getSkill() {
this.catalogService.getSkill()
.subscribe(
res => this.skills =res.json(),
error => this.errorMessage = <any>error);
}