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'}
];
}
}
When I start up the lite-server using npm start
I am receiving the following error:
[email protected] start C:\Dev\my-proj
tsc && concurrently "tsc -w" "lite-server"
app/customer/customer.service.ts(10,3): error TS7027: Unreachable code detected.
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.
If you place your whole array in a new line after the return statement, then your method has two statements:
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.
So the solution is pretty simple. Move at least the opening bracket into the line of the return statement like return [
. That's it.
I tweaked it a bit. This should work:
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;
}
}
or if you want the original the new array needs to start on the same line:
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'}
];
}
}
It usually happens when you put some code after a return statement, or when you have a return inside of an if statement and you forget the else code.
...
return warning;
this.methodUnreacheable();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With