错误TS7027:在Angular2 TypeScript Service类中检测到无法访问的代码 [英] error TS7027: Unreachable code detected in Angular2 TypeScript Service class

查看:227
本文介绍了错误TS7027:在Angular2 TypeScript Service类中检测到无法访问的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将继续学习PluralSight课程,并练习在Angular2中编写基本服务.我有以下服务文件:

I am following along with a PluralSight course and practicing writing a basic service in Angular2. I have the following service file:

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服务器时,出现以下错误:

When I start up the lite-server using npm start I am receiving the following error:

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块时,lite服务器启动正常,因此似乎有些不喜欢它的返回.任何帮助将不胜感激.

When I comment out the return block, the lite-server starts fine, so it seems to be something in that return it does not like. Any help would be appreciated.

推荐答案

如果将整个数组放在return语句之后的新行中,则您的方法有两个语句:

If you place your whole array in a new line after the return statement, then your method has two statements:

  • 返回未定义
  • 数组定义

您看到的错误非常有帮助.TypeScript告诉您,某些代码(数组定义)永远无法到达,因为您已经在到达数组行之前从函数中返回了.

The error you see is a pretty helpful one. TypeScript tells you that there is code (the array definition) that could never be reached, because you are returning from the function already before the array line can be reached.

因此解决方案非常简单.至少将左方括号移到return语句的行中,如 return [.就是这样.

So the solution is pretty simple. Move at least the opening bracket into the line of the return statement like return [. That's it.

这篇关于错误TS7027:在Angular2 TypeScript Service类中检测到无法访问的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆