【问题标题】:TypeError: Cannot read property ‘map’ of undefined [closed]TypeError:无法读取未定义的属性“地图”[关闭]
【发布时间】:2019-12-24 13:57:11
【问题描述】:

我正在使用 angular fullCalendar,但出现错误。

service.ts

getEvents()
  {
    return this.http.get('http:///api/lessons') .map( response => {
      return response.json().data.map((data) => {
            return {...data,start: data.start_time};
          });
   }); 
  }

home.ts

 ngOnInit(){
    this.events = this.service.getEvents().subscribe(events => {this.events = events;});
}

我遇到了这个错误:

TypeError: 无法读取未定义的属性“地图”

【问题讨论】:

  • 你能在stackblitz.com上创建一个例子吗?我猜你不需要response.json()
  • 响应是否包含数据?
  • @wentjun,请不要添加问题不涉及的标签。您建议使用 RxJs 作为解决方案这一事实并不能使问题适合该标签。 OP 在他们的问题中使用常规 JS .map

标签: javascript angular ionic-framework fullcalendar


【解决方案1】:

您应该使用 RxJS 的 map 运算符。请注意,它与 JavaScript 的 Array.map() 不同。

此外,对于 RxJS 6+,您应该使用 pipeable operators,因此使用 pipe() 函数。

import { map } from 'rxjs/operators';

getEvents() {
  return this.http.get('http:///api/lessons') 
    .pipe(
      map(response => {
        return response.map((data) => {
          return {...data,start: data.start_time};
        });
     })
  ); 
}

此外,在您的 component.ts 上,console.log() 语句应在 subscribe() 内处理,因为 HTTP 请求本质上是异步的。将它放在外面会导致它显示为undefined

ngOnInit(){
  this.service.getEvents().subscribe(events => {
    this.events = events;
    console.log(this.events);
  });
}

【讨论】:

  • 我仍然遇到同样的错误,请帮助我
  • @B.T 嘿,我已经更改了我的答案。我犯了一个错误。参考return response.map.. 应该可以解决你的问题!让我知道它是否有效
  • 我有这个错误 TypeError: response.map is not a function.
  • 我认为那是因为我使用了两张地图
  • 但是我必须使用两张地图我应该怎么做请帮助我
【解决方案2】:

看起来您使用的是旧的 http, 请更新到 HttpClient,这样你就不需要了

`return response.json().data.map((data) => {
        return {...data,start: data.start_time};
      });`

只需return response(data => { return {...data,start: data.start_time}; });

【讨论】:

猜你喜欢
  • 2019-04-09
  • 2022-01-14
  • 2019-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多