简体   繁体   中英

if else error in typescript , angular 6 project in vscode

I am new to typescript and I am trying to build a file with constants in a angular 6 ionic/cordova project. I created a service file through the angular cli with ng generate service appboot

I want to create a simple if else ,I've searched and nothing should be wrong with my if else but I get a vscode error saying I am missing a ",". And I also get an error when I run ionic serve. The error only appears when I try to type the else

In my appboot.service.ts I have:

import { Injectable, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { environment } from '../environments/environment';


@Injectable({
  providedIn: 'root'
})
export class AppbootService {


env: string;

  constructor() {

  }

if(env == "dev")



}else {}

Statements can't appear randomly inside a class body, they need to appear in method or constructor body. For example:

import { Injectable, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { environment } from '../environments/environment';


@Injectable({
    providedIn: 'root'
})
export class AppbootService {


    env: string;

    constructor() {
        // Assuming env gets set somehow before the if 
        if (this.env == "dev") {

        } else { }
    }
}

Also field access nees to be prefixed with this.

Your condition is outside the class.

Your condition could be in the constructor... :

import { Injectable, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { environment } from '../environments/environment';

@Injectable({
    providedIn: 'root'
})
export class AppbootService {

    env: string;

    constructor() {
        if (this.env == "dev") {

        } else { }
    }
}

...it could also be in the ngOnInit life cycle... :

import { Injectable, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { environment } from '../environments/environment';

@Injectable({
    providedIn: 'root'
})
export class AppbootService implements OnInit {

    env: string;

    constructor() {}

    ngOnInit() {
        if (this.env == "dev") {

        } else { }
    }
}

...or simply in a new function. :

import { Injectable, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { environment } from '../environments/environment';

@Injectable({
    providedIn: 'root'
})
export class AppbootService implements OnInit {

    env: string;

    constructor() {}

    ngOnInit() {}

    myfunction() {
        if (this.env == "dev") {

        } else { }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM