console.log在Angular2组件(Typescript)中不起作用 [英] console.log not working in Angular2 Component (Typescript)
问题描述
我对Angular2和Typescript都比较陌生.由于typescript是javascript的超集,因此我希望像console.log
这样的功能可以正常工作. console.log
在组件类外部时可以在.ts
文件中完美运行,但不能像我期望的那样从组件类内部运行.
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.
}
有什么我想念的吗?
推荐答案
它不起作用,因为console.log()不在类"App"的可执行区域"中.
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.
执行代码的唯一方法是将其放在要执行的方法中.例如:constructor()
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)
}
}
像普通的javascript对象一样思考类.
Think of class like a plain javascript object.
期望它能奏效吗?
class: {
s: string,
console.log(s)
}
如果仍然不确定,请尝试打字机游乐场,在这里您可以看到您的打字机代码已生成为纯JavaScript.
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
这篇关于console.log在Angular2组件(Typescript)中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!