注入组件Angularjs2

时间:2015-09-22 16:47:27

标签: typescript angular

我只是在测试Angularjs2.0但是我遇到了向一个类注入服务的问题。这是我的代码:

import {Component, View, bootstrap, NgFor, HttpService, Promise} from 'angular2/angular2';

@Component({
    selector: 'meeting-form',
    appInjector: [MeetingService]
})

@View({
    template: `
        <ul>
            <li *ng-for="#meeting of meetings">
                Meeting Room: meeting room {{meeting.room}}
                Date: {{meeting.date}}
                Time: {{meeting.time}}
            </li>
        </ul>
            <select #room>
                <option value="1">Meeting Room 1</option>
                 <option value="2">Meeting Room 2</option>
            </select>
            <input type="date" #date>
            <input type="time" #time>
            <button (click)="reserveMeeting(room.value, date.value, time.value)">Reserve</button>

    `,
    directives: [NgFor]
})

class MeetingFormComponent{
    meetings: Array;

    constructor(meetingService: MeetingService){
        this.meetings = meetingService.getMeetings();
    }

    reserveMeeting(room: number, date: string, time: string, meetingService: MeetingService){
        meetingService.postMeeting(room, date, time);
    }
}

class MeetingService {
    http: HttpService;

    constructor(http: HttpService) {
        this.http = http;
    }
    getMeetings() {
        return this.http.get('/meetings').then(function(data){
            return data.meetings;
        })
    }

    postMeeting(room: number, date: string, time: string){
        return this.http.post('/meetings', {"room": room, "date": date, "time": time}).then(function(data){
           return data.meeting;
        })
    }
}

bootstrap(MeetingFormComponent);

我收到此错误:

EXCEPTION: Error during instantiation of Token(Promise<ComponentRef>)!. ORIGINAL EXCEPTION: Cannot resolve all parameters for MeetingFormComponent(undefined). Make sure they all have valid type or annotations.

我正在查看文档,看起来这正是他们注入服务的方式。我错过了一步吗?我也试过引导服务类但是没有用。

1 个答案:

答案 0 :(得分:5)

将您的服务标记为可注射,如下所示:

import {Injectable} from 'angular2/core';

@Injectable()
class MeetingService { ... }

您可以详细了解 HERE

更新如果您的代码全部在1文件中,如上所示,那么您需要将服务定义移到组件上方,因为ES6(ES2015)中的类不是功能在ES5中悬挂。