console.log not working in Angular2 Component (Typescript)

后端 未结 3 977
感情败类
感情败类 2020-12-05 13:05

I am relatively new to both Angular2 and typescript. Since typescript is a superset of javascript, I\'d expect functions like console.log to work. console

相关标签:
3条回答
  • 2020-12-05 13:55

    It's not working because console.log() it's not in a "executable area" of the class "App".

    A class is a structure composed by attributes and methods.

    The only way to have your code executed is to place it inside a method that is going to be executed. For instance: constructor()

    console.log('It works here')
    
    @Component({..)
    export class App {
     s: string = "Hello2";
                
      constructor() {
        console.log(this.s)            
      }            
    }

    Think of class like a plain javascript object.

    Would it make sense to expect this to work?

    class:  {
      s: string,
      console.log(s)
     }

    If you still unsure, try the typescript playground where you can see your typescript code generated into plain javascript.

    https://www.typescriptlang.org/play/index.html

    0 讨论(0)
  • 2020-12-05 14:03

    Also try to update your browser because Angular need latest browser. check: https://angular.io/guide/browser-support

    I fixed console.log issue after updating latest browser.

    0 讨论(0)
  • 2020-12-05 14:06

    The console.log should be wrapped in a function , the "default" function for every class is its constructor so it should be declared there.

    import { Component } from '@angular/core';
    console.log("Hello1");
    
     @Component({
      selector: 'hello-console',
    })
        export class App {
         s: string = "Hello2";
        constructor(){
         console.log(s); 
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题