【问题标题】:Angular 2 observable-subscribe showing undefinedAngular 2 observable-subscribe 显示未定义
【发布时间】:2017-04-06 11:38:59
【问题描述】:

我面临的挑战与 SO Post here 中的面孔相同 请参阅下面的代码 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

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);
}

【问题讨论】:

    标签: angular typescript rxjs observable angular-http


    【解决方案1】:

    当您使用{} 时,它需要从function 显式返回。所以你必须从map函数返回&lt;Payitem[]&gt;response.json()

    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);
    }
    

    【讨论】:

    • 您救了我的命,先生!谢谢
    猜你喜欢
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 2021-03-07
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多