嗨,我正在实施一个 observable 来获取我的技能 api,但我目前在映射请求的数据时遇到了问题。我的数组在请求结束时保持为空,我认为我的问题出在 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
}
]
我很感激帮助解决这个问题。