我试图从Angular调用一个API,但得到这个错误:

属性“map”在类型“Observable<Response>”上不存在

这个类似问题的答案并没有解决我的问题:Angular 2 beta版。17:属性“map”在类型“Observable<Response>”上不存在。

我使用的是Angular 2.0.0-beta.17。


当前回答

你需要导入map操作符:

import 'rxjs/add/operator/map'

或者更一般地说:

import 'rxjs/Rx';

注意:对于RxJS 6.x版本。X和以上,你将必须使用可管道的操作符,如下面的代码片段所示:

import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

// ...
export class MyComponent {
  constructor(private http: HttpClient) { }
  getItems() {
    this.http.get('https://example.com/api/items').pipe(map(data => {})).subscribe(result => {
      console.log(result);
    });
  }
}

这是由于RxJS团队删除了对使用的支持 更多信息请参见RxJS更新日志中的重大更改。

更新日志如下:

operator:可管道操作符现在必须像这样从rxjs中导入:import {map, filter, switchMap} from 'rxjs/operators';没有深度进口。

其他回答

  import { Injectable } from '@angular/core';
  import { Http } from '@angular/http';
  import 'rxjs/add/operator/map';

  @Injectable({
  providedIn: 'root'
  })
  export class RestfulService {

  constructor(public http: Http) { }

 //access apis Get Request 
 getUsers() {
 return this.http.get('http://jsonplaceholder.typicode.com/users')
  .map(res => res.json());
  }

 }

执行命令

 npm install rxjs-compat 

我只需要导入

 import 'rxjs/add/operator/map';

重新启动vs代码,问题解决。

在angular的新版本的httpClient模块中,你还没有这样写:

return this.http.request(request)
      .map((res: Response) => res.json());

但你可以这样做:

return this.http.request(request)
             .pipe(
               map((res: any) => res.json())
             );

只需安装rxjs-compat就可以解决这个问题

npm i rxjs-compat --save-dev

然后像下面这样导入它

import 'rxjs/Rx';

你需要导入map操作符:

import 'rxjs/add/operator/map'

或者更一般地说:

import 'rxjs/Rx';

注意:对于RxJS 6.x版本。X和以上,你将必须使用可管道的操作符,如下面的代码片段所示:

import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

// ...
export class MyComponent {
  constructor(private http: HttpClient) { }
  getItems() {
    this.http.get('https://example.com/api/items').pipe(map(data => {})).subscribe(result => {
      console.log(result);
    });
  }
}

这是由于RxJS团队删除了对使用的支持 更多信息请参见RxJS更新日志中的重大更改。

更新日志如下:

operator:可管道操作符现在必须像这样从rxjs中导入:import {map, filter, switchMap} from 'rxjs/operators';没有深度进口。

我有同样的问题,我解决它如下

import { map } from 'rxjs/operators'; // imports statement 

return this.auth.user$.pipe(
  map(user =>{
    if(user) return true;
        this.router.navigate(['/login'], { queryParams: {returnUrl :state.url}});
    return false;
  }));
}

有一个问题,可观察类型是空的,所以我添加类型任何,它有助于清除许多错误

user$: Observable<firebase.User | any>;