【发布时间】: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