2016-12-12 48 views

回答

0

要獲得可觀察的,您可以按照下面的示例。 getStories方法使用注入的HTTP服務並返回一個可觀察值,它可以進一步用於獲取響應。

@Injectable() 
export class StoriesService { 

    constructor(private http:Http,private constService :ConstantsService) { } 

    public getStories() 
    { 
     this.http 
      .get(this.constService.apiBaseUrl + "Stories/Stories") 
      .subscribe ((data: Response) => console.log(data)); 
    } 
} 

這是一個簡單的HTTP獲取服務示例。

3

創建類似的服務:

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 
import 'rxjs/Rx'; 
import {Observable} from 'rxjs/Rx' 

export class MyService { 
    constructor(public http: Http) { } 

    private extractData(res) { 

    if (res.status < 200 || res.status >= 300) { 
     throw new Error('Bad response status: ' + res.status); 
    } 

    // console.log(res.json()); 
    this.serviceData = (res.json()); 
    return this.serviceData || {}; 
    } 

    loaddata(): Observable<any> { 
    return this.http.get(this.server_url) // define a variable server_url to assign the requested url 
     .map(this.extractData); 
    } 
} 

現在在組件的ngOnInit方法通過調用該服務的方法得到的值。

class MyComponent{ 
    constructor(public _myService: MyService) 
    ngOnInit(){ 
     this._myService.loaddata().subscribe(data => { 
     // do something with the data 
    }) 

    } 
} 
+0

在.map()之後使用.subscribe總是很重要嗎? –

+0

@techiequestie,是的,這很重要。由於API例如'loaddata'返回一個Observable,我們需要訂閱它來實際執行http請求。 – Emu