2017-01-16 86 views
-1

當我以角度編寫服務時,我反覆看到一個名爲'Observable'的單詞。 我的接口,爲什麼observables被用於角度2

export interface IDetails{ 
       custominfo:string; 
    } 

我的服務,

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

@Injectable() 
export class GetAllList { 
    id = this.loc._id; 
    private _productUrl = 'http://localhost:3000/getprofilebyid/'+this.id; 

    constructor(private _http: Http) { } 
    getList(): Observable<IDetails[]> { 
     return this._http.get(this._productUrl) 
     .map((response: Response) => { return <IDetails[]> response.json().data; 
     }); 

    } 
} 

我有兩個疑問,

1)爲什麼我所有的變量是我得到的HTTP調用的結果的聲明文件稱爲「界面」。

2)在我的代碼中,'Observable'這個詞有什麼用處。

任何人都可以請help.Thanks提前。

回答

1

Observable是Promise的強大替代品。 您可以將其視爲事件流。因此,無論何時發生觀察事件,用戶都會收到通知。

實施例:

getList(): Observable<IDetails[]> { 
     return this._http.get(this._productUrl) 
     .map((response: Response) => { return <IDetails[]> response.json().data; 
     }); 

    } 

這裏的GetList()方法有返回類型可觀察可訂閱得到含有式IDetails的元件的陣列。

用法:

export class SomeComponent { 
    constructor(private getAllList:GetAllList) 
    this.getAllList.getList().subscribe(
     (data)=>{ 
      //do something with the array containing elements of type IDetails 
      console.log(data); 
     }), 
     (error)=>{ 
      // handle error 
      console.log(error); 
     }), 
     ()=>{ 
      // On Compete 
      console.log("Subscription completed") 
     }) 
} 

對於進一步閱讀: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html

+0

嗨JSNinja,爲什麼我需要聲明我的getcall結果的名字iDetails? – MMR

+0

這是Observable在訂閱時提供的類型。例如,可觀察的或可觀察的將分別提供字符串布爾值。 – JSNinja

+0

那麼要使用observables我應該聲明的類型? – MMR