ThreeAccents
ThreeAccents

Reputation: 1882

Injecting components Angularjs2

I'm just testing out Angularjs2.0 but I'm running into issue injecting a service to a class. Here is my code:

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);

I get this error:

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.

I'm looking at the docs and it seems like that is exactly how they are injecting their service. Am I missing a step? I've also tried bootstraping the service class but that didn't work.

Upvotes: 5

Views: 481

Answers (1)

Brocco
Brocco

Reputation: 65053

Mark your service as injectable like this:

import {Injectable} from 'angular2/core';

@Injectable()
class MeetingService { ... }

You can read more about that HERE

Update if your code is all in 1 file as you have it shown above, then you will need to move the definition of your service above the component, because classes in ES6 (ES2015) are not hoisted as functions are in ES5.

Upvotes: 5

Related Questions