【问题标题】:Passing a variable in angular2在angular2中传递一个变量
【发布时间】:2016-11-24 01:56:56
【问题描述】:

我正在尝试将值从 html 文件传递​​到我的组件,然后将其添加到我的 json 提要 url。

我已经设法将它放到组件中并打印到 html 文件中,但是你无法将它附加到我的 json 提要 url 的末尾。

这个组件和html文件直接来自anguler2 cli

app.component.ts

import { Component } from '@angular/core';
import {Http} from '@angular/http';
import {HTTP_PROVIDERS} from '@angular/http';

@Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class AppComponent {
  title = 'app works!';

  values = '';
   onKey(value: string) {
    this.values = value + ''; // pass this value to the url below
  }


    people: Array<Object>;
    constructor(http:Http) {
        http.get('http://myurl.com/json_feed.php?q=' + this.values) // get the value from above
        .subscribe(res => {
        this.people = res.json();
      })
    }

}

app.component.html

<h1>
  {{title}}
</h1>

<input #box (keyup)="onKey(box.value)">

{{values}}

<ul *ngFor="let person of people">
  <li class="text">
    {{person.model}}
  </li>
</ul>

【问题讨论】:

  • 看起来有点奇怪。 http.get(...) 代码在创建组件时作为第一件事执行,但 onKey(...) 仅在稍后按下键时执行。那是行不通的。您需要将http.get... 移动到onKey(),其中values 已更新。
  • 我试图将构造函数放在 onKey 函数中,但它给出了一个错误提示“找不到构造函数”,我是打字稿的新手,它有一些奇怪的陷阱
  • 我不是说构造函数。我的意思是构造函数的内容。您不能在另一个方法中移动构造函数。

标签: angularjs json typescript angular


【解决方案1】:

这是向流附加值的错误语法。 this.values = value + '';

它所做的是一次又一次地覆盖旧值。因此正确的代码是 this.values = this.values + value + '';

【讨论】:

  • 伟大的收获!我不明白这与stream 有什么关系。我猜你的意思是string
  • 不幸的是,它附加到 {{values}} 但在删除时不会更改并且它不会将值传递给 url
【解决方案2】:

正如 Günter Zöchbauer 所说,构造函数是在构建组件时执行的,您不能使用它来更新值。你必须这样做:

export class AppComponent {

  ...

  values = '';

  onKey(value: string) {

    this.values += value + '';

    getData(); // call getData method
  }

  people: Array<Object>;

  constructor(public http: Http) {

  }

  getData(){

      this.http.get('http://myurl.com/json_feed.php?q=' + this.values)
      ...

    })
  }

}

另外请注意,如果您在 main.ts 中引导应用程序时未提供 HTTP_PROVIDERS,则您的 http 请求将不起作用。

【讨论】:

  • 我终于让它工作了构造函数(http: Http) { this.http = http; } 和 getData(){ this.http.get('myurl.com/json_feed.php?q=' + this.values) ... })
  • 好的,我已经更新了答案,还显示了 http 提供程序的正确使用。问候
  • 您好,我们只需要在构造函数中使用this.http=http;,否则它将不起作用constructor(public http: Http) { this.http = http; }
  • 如果你使用:constructor(public http: Http),你可以避免使用:this.http = http;。这是实例化服务的捷径。
猜你喜欢
  • 2012-07-19
  • 1970-01-01
  • 1970-01-01
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-07
  • 2022-01-06
相关资源
最近更新 更多