【发布时间】:2016-02-22 12:10:54
【问题描述】:
我想将一个字符串参数传递给我的组件。根据传递参数,我将为组件中的服务传递不同的参数。我下一步要做:在 index.html 中调用我的组件,传递参数。
<top [mode]="tree">Loading...</top>
在我的组件中,我包含来自 angular2/core 的输入
import {Input, Component, OnInit} from 'angular2/core';
在我的组件类中我声明了一个输入
@Input() mode: string;
并且使用 console.log() 我试图捕捉我传递的“树”参数,但它是未定义的。
console.log(this, this.mode);
一个组件文件的完整代码:
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import {Input, Component, OnInit} from 'angular2/core';
import {ParticipantService} from '../services/participant.service';
import {orderBy} from '../pipes/orderby.pipe';
@Component({
selector: 'top',
templateUrl: 'dev/templates/top.html',
pipes: [orderBy],
providers: [HTTP_PROVIDERS, ParticipantService]
})
export class AppTopComponent implements OnInit {
constructor (private _participantService: ParticipantService) {}
errorMessage: string;
participants: any[];
@Input() mode: string;
ngOnInit() {
console.log(this, this.mode);
this.getParticipants('top3');
var self = this;
setInterval(function() {
self.getParticipants('top3');
}, 3000);
}
getParticipants(public mode: string) {
this._participantService.getParticipants(mode)
.then(
participants => this.participants = participants,
error => this.errorMessage = <any>error
);
}
}
【问题讨论】:
-
不要在你的根组件中做这些事情。它的目的只是为了保存应用程序,而不是用作组件本身。从第一个子组件开始,您将避免所有那些丑陋的变通方法。
标签: javascript typescript angular