Angularjs2 Injection Components

I am just testing Angularjs2.0, but I am having a problem with embedding a service in 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 look at the documents, and it seems that this is how they implement their services. Did I miss a step? I also tried the bootstraping class of service, but this did not work.

+5
source share
1 answer

Mark your service as injectable, for example:

 import {Injectable} from 'angular2/core'; @Injectable() class MeetingService { ... } 

You can learn more about this HERE.

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

+5
source

Source: https://habr.com/ru/post/1232041/


All Articles