从 HTML 文件中的 TypeScript (.ts) 获取值。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37198958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:28:36  来源:igfitidea点击:

Get value from TypeScript (.ts) in HTML file.

javascripthtmltypescriptangular

提问by Roka545

I'm new to Typescript and HTML. I'm building an Angular2 app and I currently have a TypeScript file that looks like this:

我是 Typescript 和 HTML 的新手。我正在构建一个 Angular2 应用程序,我目前有一个如下所示的 TypeScript 文件:

import {Http, Headers} from 'angular2/http';
import {Component} from 'angular2/core';
import {CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/common';
import {Router} from 'angular2/router';
import {Routes} from '../routes.config';

@Component({
    selector: 'home',
    templateUrl: './app/home/home.html',
    directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]
})
export class Home {
    public jsonResponse: string = "";

    constructor(private _http: Http) {
        var thisReference = this;
        thisReference.getSensors();
    }

    getSensors() {
        this.jsonResponse = "testResponse";
    }
}

I'm trying to figure out how to get the value for "jsonResponse" in an HTML file. I've searched but can't find a straightforward way to access the jsonResponse variable - any ideas?

我想弄清楚如何在 HTML 文件中获取“jsonResponse”的值。我已经搜索过但找不到访问 jsonResponse 变量的直接方法 - 有什么想法吗?

回答by Som

Here is what you are looking for: link to working code: https://plnkr.co/edit/Y6TeraRZT2NDnHMRB9B0?p=info

这是您要查找的内容:工作代码链接:https: //plnkr.co/edit/Y6TeraRZT2NDnHMRB9B0?p=info

import {Component} from '@angular/core'
@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>jsonResponse:  {{jsonResponse}}</h2>

    </div>
  `,
  directives: []
})
export class App {
  jsonResponse: string;

  constructor(){
    this.getSensors();
  }

  private getSensors() {
    this.jsonResponse = 'testResponse';
  };
}

回答by Günter Z?chbauer

There is also the jsonpipe

还有json管子

{{jsonResponse | json}}