Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of this error "Declaration of instance field not allowed after declaration of instance method."

In my Angular2 project I receiving this error:

"Declaration of instance field not allowed after declaration of instance method. Instead, this should come at the beginning of the class/interface. (member-ordering)"

I would like to understand how to resolve this and why I'm getting this.

The error is related to the private function in the next code:

export class HomeComponent implements OnInit {
public error: string;
public shirts = [];


constructor(public rest: RestService,
            public scService: ShoppingCartService,
            public snackBar: MdSnackBar) {
}


ngOnInit() {
    this.rest.getAll().subscribe((r: any) => {
        this.shirts = r;
    }, error => {
        this.error = 'Opps there\'s some error';
    });

}

addToCart(shirt: any) {
    this.scService.add(shirt);
    this.showSnackMessage('Added to Chart List');
}

showSnackMessage(message: string) {
    this.snackBar.open(message, null, {
        duration: 1000
    });
}
//Here the error is showed
private sizeScore = {
    'string': -1,
    s: 0,
    m: 1,
    l: 2,
    'x-large': 3,
};

sortData(sort: Sort) {
    const data = this.shirts.slice();
    if (!sort.active || sort.direction === '') {
        this.shirts = data;
        return;
    }

    this.shirts = data.sort((a, b) => {
        let isAsc = sort.direction === 'asc';
        switch (sort.active) {
            case 'colour':
                return compare(a.colour, b.colour, isAsc);
            case 'size':
                return compare(this.sizeScore[a.size], this.sizeScore[b.size], isAsc);
            default:
                return 0;
        }
    });
}
}
like image 890
Jakub Avatar asked Aug 04 '17 20:08

Jakub


3 Answers

I would guess that your project has some type of linting set up that checks for style issues at build time.

To fix it you just need to do as it says. Move the code up to before any method calls.

export class HomeComponent implements OnInit {
public error: string;
public shirts = [];
private sizeScore = {
    'string': -1,
    s: 0,
    m: 1,
    l: 2,
    'x-large': 3,
};
// ...
like image 99
DeborahK Avatar answered Oct 10 '22 14:10

DeborahK


It's not actually a compilation/runtime error, but a code linting issue.

It's a good practice to place all properties of your class above the methods, so if you just move private sizeScore to the top, it will stop saying.

More information about this rule here.

like image 35
Edmundo Rodrigues Avatar answered Oct 10 '22 14:10

Edmundo Rodrigues


Per the TSLint docs I think you just need to move your declaration of the field above the declarations of those methods.

like image 42
arthurakay Avatar answered Oct 10 '22 15:10

arthurakay