gpt4 book ai didi

typescript - 注入(inject)组件Angularjs2

转载 作者:太空狗 更新时间:2023-10-29 17:35:07 25 4
gpt4 key购买 nike

我只是在测试 Angularjs2.0,但在向类注入(inject)服务时遇到了问题。这是我的代码:

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.

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

最佳答案

像这样将您的服务标记为可注入(inject):

import {Injectable} from 'angular2/core';

@Injectable()
class MeetingService { ... }

您可以阅读更多有关 HERE 的信息

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

关于typescript - 注入(inject)组件Angularjs2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32722432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com