Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 views
in Technique[技术] by (71.8m points)

angular - console.log not working in Angular2 Component (Typescript)

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.log works perfectly in .ts files when outside a component class but does not work as I'd expect from inside the component class.

// main.ts

import { Component } from '@angular/core';
console.log("Hello1"); //1. This works perfectly

@Component({..)
export class App {
 s: string = "Hello2";
 // console.log(s); //2. This gives compilation error (when uncommented)
 // Error: Function implementation is missing or not immediately following the declaration.
}

Is there anything that I am missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)            
  }            
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...