2017-01-16 5 views
-1

제가 각도로 서비스를 쓰고있을 때, 나는 'Observable'이라는 단어를 반복적으로 보았습니다. 내 인터페이스,왜 observables가 angle 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; 
     }); 

    } 
} 

나는이 의심, 내가 HTTP 호출의 결과로 얻을 내 모든 변수는 왜

1)가 선언되어 있습니다 파일을 '인터페이스'라고합니다.

2) 내 코드에서 'Observable'이라는 단어를 사용하는 것은 무엇입니까?

아무도 도와주세요. 미리 감사드립니다.

답변

1

관찰 가능은 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이 구독 할 때 제공 할 형식입니다. 예 : Observable 또는 Observable 은 각각 부울 값 문자열을 제공합니다. – JSNinja

+0

observables를 사용하려면 타입을 선언해야합니까? – MMR