Angular 2 observable-subscriptions showing undefined

I have the same problem as the faces in SO Post here I get undefined in the subscription method in my .ts component, although I have data in my service. 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

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);
}
+1
source share
1 answer

As you used {}, it needs an explicit return from function. Therefore you need to return the function <Payitem[]>response.json()from map.

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

Otherwise, there will be a shorthand syntax below

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);
}
+5
source

Source: https://habr.com/ru/post/1661724/


All Articles