Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 392
Pranjal Mittal Avatar asked Jun 16 '16 21:06

Pranjal Mittal


People also ask

Can you console log in TypeScript?

log() Method in TypeScript. In the console. log() method, we can output a message to the web console. The message may be a single string or multiple JavaScript objects.

Does angular2 support TypeScript?

Angular 2 is built on TypeScript, which uses ES6 syntax and compiles to vanilla JavaScript. Standard ES5 JavaScript is also valid TypeScript, so you can still use your existing code.

Does console log work in angular?

log Function in Angular. console. log is a JavaScript function that logs messages to the developer's console or the browser console to the web page. This method helps Angular developers by informing them about the errors, warnings, and what is happening during the execution of their code.


2 Answers

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

like image 198
Daniel Pliscki Avatar answered Oct 22 '22 02:10

Daniel Pliscki


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

}
like image 7
SeleM Avatar answered Oct 22 '22 01:10

SeleM