cdoll
cdoll

Reputation: 85

Passing json data from http service to component Angular 2

I have separate requests.service.ts and schedule.ts. I am unable to pass the json returned from method from requests.service.ts, even though I mapped it when I returned it.

My code for request.service.ts

import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers } from "@angular/http";
@Injectable()
export class LoginService {
    constructor(public http: Http) { }    
        requestMethod() {     
           return this.http.get(url).map(res => res.json())
        }
}

My code for schedule.ts

let data = this.loginService.requestMethod();

Where data returns Observable {_isScalar: false, source: Observable, operator: MapOperator}...

Upvotes: 0

Views: 1238

Answers (1)

Artur Czopek
Artur Czopek

Reputation: 290

It is observable, no plain data. You need to subscribe it and handle it. For example:

let data;
this.loginService.requestMethod()
     .subscribe(okData => data = okData); // or this.data = okData if it's a class' field.

You can also handle what should be done if request has failed. You can refer to this documentation to learn more about subscription

Upvotes: 1

Related Questions