Angular 2可观察订阅显示未定义 [英] Angular 2 observable-subscribe showing undefined

查看:80
本文介绍了Angular 2可观察订阅显示未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正面临着与SO Post中的面孔相同的挑战在这里,即使在我的服务中,我也有数据,但在component.ts中的subscription方法中却没有定义. 见下面的代码 p.component.ts

I am having the same challenge as was faces in the SO Post here I am getting undefined in the subscribe method in my component.ts, even though in my service i have the data. See codes below p.component.ts

 private getPayItems():void{
    console.log('In getPayItems');
    this._payItemService.getPayItems()
    .subscribe(data => { 
        this.payItemArray = data;
        console.log(data);
    },
    (error:any) =>{
         this.alerts.push({ msg: error, type: 'danger', closable: true }); 
    }) 
}

p.service.ts

p.service.ts

getPayItems():Observable<Payitem[]>{

    let  actionUrl = this.url +  "/GetPayItem";

    return this._http.get(actionUrl, { headers: this.headers })
        .map((response: Response) => { 
            <Payitem[]>response.json() ;
             console.log(<Payitem[]>response.json()); //This logs the Object
        })
        .catch(this.handleError);
}

推荐答案

使用{}时,它需要从function显式返回.因此,您必须从map函数返回<Payitem[]>response.json().

As you used {} it needs explicit return from function. So you have to return <Payitem[]>response.json() from map function.

getPayItems():Observable<Payitem[]>{

    let  actionUrl = this.url +  "/GetPayItem";

    return this._http.get(actionUrl, { headers: this.headers })
        .map((response: Response) => { 
             console.log(<Payitem[]>response.json()); //This logs the Object
            return <Payitem[]>response.json() ;
        })
        .catch(this.handleError);
}

否则下面将是速记语法

getPayItems():Observable<Payitem[]>{
    let  actionUrl = `${this.url}/GetPayItem`;
    return this._http.get(actionUrl, { headers: this.headers })
        .map((response: Response) => <Payitem[]>response.json())
        .catch(this.handleError);
}

这篇关于Angular 2可观察订阅显示未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆