Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
934 views
in Technique[技术] by (71.8m points)

typescript - How to get data from observable in angular2

I am trying to print the result of http call in Angular using rxjs

Consider the following code

import { Component, Injectable, OnInit } from '@angular/core';
import { Http, HTTP_PROVIDERS } from '@angular/http';
import 'rxjs/Rx';

@Injectable()
class myHTTPService {
  constructor(private http: Http) {}

  configEndPoint: string = '/my_url/get_config';

  getConfig() {

    return this.http
      .get(this.configEndPoint)
      .map(res => res.json());
  }
}

@Component({
    selector: 'my-app',
    templateUrl: './myTemplate',
    providers: [HTTP_PROVIDERS, myHTTPService],


})
export class AppComponent implements OnInit {

    constructor(private myService: myHTTPService) { }

    ngOnInit() {
      console.log(this.myService.getConfig());
    }
}

Whenever I tried to print out the result of getconfig it always return

Observable {_isScalar: false, source: Observable, operator: MapOperator}

even though I return a json object instead.

How would I print out the result of getConfig ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to subscribe to the observable and pass a callback that processes emitted values

this.myService.getConfig().subscribe(val => console.log(val));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...