错误TS7027:在Angular2 TypeScript Service类中检测到无法访问的代码
我正在跟着一个PluralSight课程,并在Angular2中练习写一个基本的服务。 我有以下服务文件:
customer.service.ts
import { Injectable } from '@angular/core'; @Injectable() export class CustomerService { constructor() {} getCustomers() { return [ {id: 1, name: 'Ward'}, {id: 2, name: 'Joe'}, {id: 3, name: 'Bill'}, {id: 4, name: 'Bob'}, {id: 5, name: 'Levi'}, {id: 6, name: 'Brian'}, {id: 7, name: 'Susie'} ]; } }
当我使用npm start
lite-server npm start
我收到以下错误:
angular-quickstart@1.0.0 start C:\Dev\my-proj tsc && concurrently "tsc -w" "lite-server" app/customer/customer.service.ts(10,3): error TS7027: Unreachable code detected.
当我注释掉返回块时,文件服务器启动正常,所以它似乎是在它不喜欢的回报。 任何帮助,将不胜感激。
如果你在return语句之后把整个数组放在一个新行中,那么你的方法有两个语句:
- 返回undefined
- 一个数组定义
你看到的错误是一个很有帮助的错误。 TypeScript告诉你有代码(数组定义)永远不可能被达到,因为你已经在函数返回之前已经可以到达数组了。
所以解决scheme非常简单。 至less将左括号移动到return语句的返回语句行中。 而已。
我调整了一下。 这应该工作:
import {Injectable} from "@angular/core"; @Injectable() export class CustomerService { private data: Array<any>; constructor() { this.data = [ {id: 1, name: 'Ward'}, {id: 2, name: 'Joe'}, {id: 3, name: 'Bill'}, {id: 4, name: 'Bob'}, {id: 5, name: 'Levi'}, {id: 6, name: 'Brian'}, {id: 7, name: 'Susie'} ]; } getCustomers() { return this.data; } }
或者如果你想要新的数组需要在同一行开始:
import {Injectable} from "@angular/core"; @Injectable() export class CustomerService { constructor() { } getCustomers() { return [ {id: 1, name: 'Ward'}, {id: 2, name: 'Joe'}, {id: 3, name: 'Bill'}, {id: 4, name: 'Bob'}, {id: 5, name: 'Levi'}, {id: 6, name: 'Brian'}, {id: 7, name: 'Susie'} ]; } }
当你在return语句之后放置一些代码,或者当你在if语句中返回时,通常会发生这种情况,而你忘记了else代码。
... return warning; this.methodUnreacheable();
- TypeScripttypes损坏(错误TS2687):“迭代器”的所有声明必须具有相同的修饰符
- 用电子和Systemjs导入节点模块
- 导入模块上的Node.js错误
- npm ERR! 无效的名称:“@ types / handlebars”
- 如何在用Typescript和ES6编写的NodeJS中运行黄瓜testing
- 带有节点的内存中的Transpile TypeScript
- 使用TypeScript和Sails.js是给的问题,TypeError:对象不是一个函数
- 从客户端传递给nodeJS时,string转换为Object
- 什么是“js”方法在gulp上(对于使用gulp-typescript的Typescript项目)