【问题标题】:console.log not working in Angular2 Component (Typescript)console.log 在 Angular2 组件(Typescript)中不起作用
【发布时间】:2016-06-16 21:17:43
【问题描述】:

我对 Angular2 和 typescript 都比较陌生。由于 typescript 是 javascript 的超集,我希望像 console.log 这样的函数能够工作。 console.log 在组件类外部时在 .ts 文件中完美运行,但在组件类内部却无法正常运行。

// 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.
}

我有什么遗漏的吗?

【问题讨论】:

  • 你在@Component 里放了什么?您可以尝试在类中放置一个构造函数,如下所示:constructor() { console.log('test')}
  • 我认为它不起作用,因为 console.log 没有包含在函数中。可以展示一下 JS 编译后的表格吗?
  • @L.querter:console.log 在构造函数内部使用时有效,但在构造函数外部使用时不起作用,即使构造函数存在。也许将它包装在一个函数中是必要的。我不知道这一点。

标签: typescript angular


【解决方案1】:

它不起作用,因为 console.log() 它不在“App”类的“可执行区域”中。

类是由属性和方法组成的结构。

执行代码的唯一方法是将其放在将要执行的方法中。例如:constructor()

console.log('It works here')

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

把类想象成一个普通的 javascript 对象。

期望这行得通有意义吗?

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

如果您仍然不确定,请尝试 typescript playground,您可以在其中看到您的 typescript 代码生成为纯 javascript。

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

【讨论】:

  • 变量初始化也是一个表达式,我很困惑为什么它在构造函数的范围之外起作用而函数调用却不起作用。
  • 试试我上面提到的typescript playgroung,你会看到每个变量定义都被转译成一个javascript函数体。
  • 很明显的事情,我开始发疯试图解决这个问题 - 谢谢
  • 在您给出的 javascript 示例中,s:string, console.log(s) 至少不应该返回一些值仍然没有意义。它至少应该在浏览器中说 s 是字符串类型。
  • 哇,经过一个小时的搜索,这个答案终于让我想起了它。谢谢! Angular 新手在这里。
【解决方案2】:

console.log 应该包装在一个函数中,每个类的“默认”函数是它的constructor,所以它应该在那里声明。

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

 @Component({
  selector: 'hello-console',
})
    export class App {
     s: string = "Hello2";
    constructor(){
     console.log(s); 
    }

}

【讨论】:

    【解决方案3】:

    同时尝试更新您的浏览器,因为 Angular 需要最新的浏览器。 检查:https://angular.io/guide/browser-support

    我在更新最新浏览器后修复了 console.log 问题。

    【讨论】:

      【解决方案4】:

      转到设置并使用选项“恢复默认值和 relodenter image description here

      enter image description here

      【讨论】:

      • 您的回答似乎与问题无关。你有没有在错误的问题上发布它?
      • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
      • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
      猜你喜欢
      • 1970-01-01
      • 2017-06-30
      • 2017-10-10
      • 1970-01-01
      • 2017-01-29
      • 2017-09-09
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      相关资源
      最近更新 更多