0

I have a service and a component which uses the service.The issue is that in a service I can read the response which is as JSON object. But in the Component, I get the following: res: undefined.

service:

constructor(
    private http: Http,
    private fbuilder: FormBuilder,
    private user: UserService
) {}
login(uname:string, pass:string): Observable<any> {

    let headers = new Headers({
        'Content-Type': 'application/json',
        'Username':uname,
        'Password':pass
    });
    let options = new RequestOptions({ headers: headers });
    let data = {};
    var Observable = this.http.post( url, data, options )
    .map(res => {
        res.json();
    })
    .catch( (error: any) => Observable.throw(error.json().error || 'Server error') );
    return Observable;
}

component:

constructor(
    private http: Http,
    private fbuilder: FormBuilder,
    private user: UserService
) {}
loginUser(uname: string, pass: string) {
    this.user.login(uname, pass).subscribe(
        res => {
            console.log('res: ' + JSON.stringify(res));
        },
        err => {
            this.errorMessage = err;
        }
    );
}
k.vincent
  • 3,743
  • 8
  • 37
  • 74

1 Answers1

2

It looks like your problem is with this code:

.map(res => {
    res.json();
})

You're not returning the result of res.json. You just need to add the return statement, like so:

.map(res => {
    return res.json();
})

You could also just remove the {} pair, like so:

.map(res => res.json())
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
  • Ohhh. My Bad. You're right! Had the same issue before and found out that I had to return the `res.json()`. Issues solved. And yes, removing the `{}` would save some code, but I want to print out the the res. in the `console`. – k.vincent Oct 26 '17 at 08:54