【问题标题】:Angular 6 Property 'map' does not exist on type 'Object'“对象”类型上不存在 Angular 6 属性“地图”
【发布时间】:2018-11-04 18:36:00
【问题描述】:

我有一个返回对象/数组的 api,如下所示:

(2) [{...}, {...}]      object

  0: {a: '1', b: {id: '1'}}
  1: {a: '2', b: {id: '2'}}

所以它看起来像对象数组(但调试时说“对象”)。

所以在我的代码中我有:

return this.http.get(this.url).pipe(
  map(datas => {
    return datas.map(data => {
      let object = {
        a: data['a'],
        b: data['b']['id'],
      }
      return object;
    })
  })
);

但是有:

return datas.map(data => {

我遇到了一个错误:

Property 'map' does not exist on type 'Object'.

但应用程序运行良好,可以正确显示此数据。但是这个错误很烦人。

我能做什么?

【问题讨论】:

  • 你可以用(datas: Array<any>) => { ... }告诉Typescript编译器返回值的类型

标签: angular6


【解决方案1】:

试试这个:

npm install rxjs@6 rxjs-compat@6 --saven

请访问Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'了解更多。

【讨论】:

    【解决方案2】:

    以下操作符在 RXJS6 中被重命名

    catch() => catchError()
    do() => tap()
    finally() => finalize()
    switch() => switchAll()
    

    此外,一些 Observable 创建方法被重命名/重构:

    throw() => throwError()
    fromPromise() => from() (this automatically detects the type)
    

    FOR MAP 语法

    import { map } from 'rxjs/operators';
    
    myObservable
      .pipe(map(data => data * 2))
      .subscribe(...);
    

    【讨论】:

      【解决方案3】:

      我必须用 (data: any) => { ... }

      指定返回值的类型

      【讨论】:

      • 这就是我要找的!我希望这能得到更多的支持,以便人们看到。
      【解决方案4】:

      你必须像这样在 ng6 中导入地图:

      import { map } from 'rxjs/operators';
      

      【讨论】:

        【解决方案5】:

        在带有 rxjs 6.3.3 的 Angular 6x 中,您可以这样做。在文件中(app.component.ts)

        import { Component } from '@angular/core';
        import { HttpClient, HttpParams, HttpHeaders} from '@angular/common/http';
        import { Observable, throwError } from 'rxjs';
        import { map, catchError, retry } from 'rxjs/operators';
        
        @Component({
          selector: 'app-root',
          templateUrl: './app.component.html',
          styleUrls: ['./app.component.css']
        })
        
        export class AppComponent 
        {    
          _url = 'http://...';
          constructor( private http: HttpClient ) { }
          articles: Observable<any>;
        
          // Method and constructor
          getAPIRest() 
          {       
            const params = new HttpParams().set('parameter', 'value');
            const headers = new HttpHeaders().set('Autorization', 'auth-token');
            this.articles = this.http.get(this._url + '/articles', { params, headers })
                         .pipe( retry(3),
                                map((data => data),
                                catchError(err => throwError(err))));
          }
        }
        

        【讨论】:

          猜你喜欢
          • 2022-07-23
          • 2018-10-16
          • 2021-04-02
          • 2019-12-31
          • 1970-01-01
          • 2019-02-01
          • 2018-11-30
          • 2018-11-25
          • 1970-01-01
          相关资源
          最近更新 更多