【问题标题】:observables for api request in angular2angular2 中 api 请求的 observables
【发布时间】:2017-06-28 15:16:10
【问题描述】:

您好,我正在实施一个 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
    }
]

感谢帮助解决此问题。

【问题讨论】:

  • 尝试简化事情:不要使用.map(this.extractData),而是使用.map(res =&gt; res.json()).map(res =&gt; res.data || {}),看看它是否有效
  • 请求结束时我的数组保持为空 哪个数组在代码中的哪个确切点为空?你的 json 是什么样子的?
  • 如果您的 web api 返回的 JSON 字符串中没有 data 属性,那么 body.data 将始终为 null

标签: angular angular-observable


【解决方案1】:

我解决了将我的服务中的函数 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);
  }

【讨论】:

  • 就像 Jota.Toledo 说的,你遇到的错误是在这个 extractData 函数中,你的响应似乎没有 data 属性,只需将其更改为:private extractData(res: Response) { let body = res.json(); return body || [];}
猜你喜欢
  • 2016-12-27
  • 2017-08-10
  • 2016-11-08
  • 2017-01-16
  • 1970-01-01
  • 2016-04-29
  • 2015-11-12
  • 2016-09-07
  • 2017-11-05
相关资源
最近更新 更多