Tôi muốn chuyển một tham số chuỗi cho thành phần của mình. Tùy thuộc vào tham số truyền đi, tôi sẽ chuyển các tham số khác nhau cho các dịch vụ trong thành phần của tôi. Tôi làm tiếp theo: Trong index.html gọi thành phần của tôi, truyền tham số.Góc 2. Truyền tham số cho một thành phần
<top [mode]="tree">Loading...</top>
Trong thành phần của tôi bao gồm đầu vào từ angular2/lõi
import {Input, Component, OnInit} from 'angular2/core';
Trong lớp component`s của tôi tuyên bố một đầu vào
@Input() mode: string;
Và với console.log() tôi cố gắng để bắt thông số của tôi về 'cây', nhưng nó không được xác định.
console.log(this, this.mode);
Mã đầy đủ của một tập tin thành phần:
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
);
}
}
Đừng làm những việc này trong thành phần gốc của bạn. Mục đích của nó chỉ là giữ ứng dụng, không được sử dụng như một thành phần. Bắt đầu từ thành phần con đầu tiên và bạn sẽ tránh được tất cả những cách giải quyết xấu xí đó. –