【问题标题】:Error: Unreachable code detected ionic 3 weather app错误:检测到无法访问的代码 ionic 3 天气应用程序
【发布时间】:2018-11-13 20:36:55
【问题描述】:

好的,所以我正在关注 ionic 3 的 traversy 媒体教程,当我到达创建提供程序的部分时,我得到一个错误,提示在此处检测到无法访问的代码:

.map((res: Response) => res.json() );

它也写在 typescript

找不到名称“地图”,您的意思是“地图”吗?

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

@Injectable()
export class WeatherProvider {
  apiKey = "89cca14f4ffcd27d602ad5e587f8e17f";
  url;

 constructor(public http: HttpClient) {
   console.log('Hello WeatherProvider Provider');
   this.url = "api.openweathermap.org/data/2.5/weather?q=";
 }



 getWeather(city, country){
 return this.http.get(this.url+city+','+country);
   .map((res: Response) => res.json() );
 }

}

【问题讨论】:

  • 在我看来你不应该在这里使用分号(错别字?):`return this.http.get(this.url+city+','+country);` - I' m 假设 .map(...) 应该紧随其后

标签: javascript typescript ionic-framework visual-studio-code


【解决方案1】:

getWeather() 中的 return 语句使 .map() 无法访问。您应该使 return 语句成为函数中的最后一条语句。

【讨论】:

  • 实际上,只需删除返回行上的分号即可解决问题,但是如果我按照您的建议将返回行放在最后,我会遇到同样的问题
  • 其实,这就是为什么我的回答是正确的。删除分号实际上使您的 return 成为最后一条语句,因为 JS 删除了空格并将代码压缩成一行,使 return 语句成为一个表达式。
  • @lcrimsonl 你可以在这里阅读:crockford.com/javascript/encyclopedia/… 更具体地说:在下一个示例中,a ; c 后面没有插入分号,因为没有语法错误。 a = b + c (d + e).print() 理解为 a = b + c(d + e).print();这可能与意图完全不同。依赖分号插入是不明智的。它可以掩盖错误并且可能导致错误。 ----因此,您可以采取分号插入的行为并...在下面继续
  • 推断出 JS 只是顺势而为。这就是为什么当你去掉分号时,你的代码会按预期编译。这有点绕圈子,但这就是正在发生的事情。
猜你喜欢
  • 2020-08-27
  • 2011-05-09
  • 2014-11-20
  • 2018-10-04
  • 2015-02-08
  • 1970-01-01
  • 2020-07-18
  • 2010-12-01
相关资源
最近更新 更多