본문 바로가기

Trouble Shooting

Angular, error TS2339: Property 'map' does not exist on type 'Observable<Object>'

Angular를 공부하던 중, 책에서 안내한데로 아래의 코드들을 구현했으나, 제목처럼 오류가 발생했다.


import 'rxjs/add/operator/map';

...

ngOnInit() {

     this.postsService.getPosts()

       .map(res => res['items'])

       .subscribe((result: any) => this.posts = result)

}


error TS2339: Property 'map' does not exist on type 'Observable<Object>'


RxJS

RxJS는 자바스크립트에 기반한 Reactive Extensions 라이브러리이다. 여기서 Reactive는 ReactiveX인데, observer 패턴을 응용 이벤트기반 비동기 프로그래밍을 가능케 해주는 라이브러리이다. 현재 버전6이 발표된 상태이다. 링크된 사이트를 방문하면 확인할 수 있다. [RxJS version 6] 


오류 원인 및 해결법

오류의 원인은 책에서 RxJS 옛 버전에 기반한 코드를 소개했기 때문이다. 아래처럼 버전 5에 기반한 코드로 변경하면 된다.


옛 버전 :

import 'rxjs/add/operator/map';


버전 5.x:

import { map } from 'rxjs/operators';


옛 버전:

this.postsService.getPosts()

       .map(res => res['items'])


버전 5.x:

this.postsService.getPosts()

      .pipe(map(res => res['items']))