ts Property 'map' does not exist on type &

2019-07-14 05:13发布

问题:

This question already has an answer here:

  • Property 'map' does not exist on type 'Observable<Response>' 21 answers

I'm new to angular and npm, but when learning, I got an error, with a code that seems to work on the source I'm trying to reproduce(here).

I assume this has to do with my development environment but I can't exactly understand why.

This is my code:

return this.http.get('api/cards.json')
 .map((response:Response) => <Card[]>response.json().data)
 .do(data=>console.log(data))
 .catch(this.handleError);

On the .map, Visual Studio Code give me this error:

ts Property 'map' does not exist on type 'Observable'

If I ignore this error and go to the browser, I've the same message.

I've created my project with the angular-cli, and my angular-version is actually the 2.4.4. The server is running with the ng serve tool.

I've made somes searches:

property map does not exist on observable response in angular --> I don't use visual studio 2015, also, I'm up to date with my Visual Studio Code(also it seems the bug has ben solved since a while).

Angular 2 2.0.0-rc.1 Property 'map' does not exist on type 'Observable<Response>' not the same as issue report --> My commandline doesn't know anything about tsc and after I've done the npm i typescript -g(and restarted both VS code and the ng serve

Any idea what is going wrong(I suppose something is not up to date, but I don't know what and how to update it).

回答1:

You have to reference the RxJs library in your module/component/service (whatever it is you are writing here) as Observable (the type returned from http.get) is a part of that library. The RxJs has many operators that you can use like map, catch, do, etc but in order to use these you must reference the files/modules that they are contained in.

The tutorials on the angular site have a good explanation on how you consume the Observable<T> and how to create a reference mapping to the more common methods you want to use like map in the RxJs lib. By creating a single file with references to the more commonly used operators and types in the RxJs library you only have to then reference that reference file where you want to consume those types which saves on having to re-add all the operators/types in every file across your project where you want to take advantage of them.

Here is an example file (named rxjs-operators.ts for this example) with some of the more commonly used methods.

// Observable class extensions
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/throw';

// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';

To the top of your file you want to use .map (or any other method) add this line.

import './rxjs-operators';