我刚开始学习angular2.0。我已经使用了angular1中的服务。但我不知道如何在angular2中使用服务 这是我的component.html文件:
<form [ngFormModel]="loginForm" (click)="doLogin($event)">
<input ngControl="email" type="email" placeholder="Your email" required>
<input ngControl="password" type="password" placeholder="Your password" required>
<button type="submit">Log in</button>
</form>
这是我的打字稿文件:
import {Component} from 'angular2/core';
import {FORM_DIRECTIVES,CORE_DIRECTIVES,FormBuilder, Validators,Control,ControlGroup } from 'angular2/common';
import { SampleService } from './sample.service';
@Component({
selector: 'my-form',
templateUrl: 'app/form.component.html'
providers: [
SampleService
]
})
export class FormComponent {
//loginForm: ControlGroup;
constructor(fb: FormBuilder) {
this.loginForm = new ControlGroup({
email: new Control("", Validators.required),
password: new Control("", Validators.required)
});
}
constructor(private _sampleService: SampleService){
this._sampleService = _sampleService;
}
doLogin(event){
this._sampleService.login()
.subscribe(
data => /*this.countries = data,
error => this.error = "Region " + this.region + " is invalid."*/
{
this.countries = data;
}
);
}
};
我已经创建了Sample服务来获取数据。
import { Hero } from './hero';
import { Injectable } from 'angular2/core';
import {Http} from 'angular2/http';
import 'rxjs/Rx';
import {AppSettings} from './appSettings';
@Injectable()
export class SampleService {
constructor(http: Http){
this.http = http;
}
login(data){
return this.http.get(AppSettings.API_ENDPOINT+"oceania").map(res => res.json(), err => err);
}
}
错误是:
this._sampleService.login() is undefiend
答案 0 :(得分:3)
此类有两个不受支持的构造函数。您需要将它们合并为一个
export class FormComponent {
//loginForm: ControlGroup;
constructor(fb: FormBuilder) {
this.loginForm = new ControlGroup({
email: new Control("", Validators.required),
password: new Control("", Validators.required)
});
}
constructor(private _sampleService: SampleService){
this._sampleService = _sampleService;
}
doLogin(event){
this._sampleService.login()
.subscribe(
data => /*this.countries = data,
error => this.error = "Region " + this.region + " is invalid."*/
{
this.countries = data;
}
);
}
}
像
export class FormComponent {
//loginForm: ControlGroup;
constructor(fb: FormBuilder, private _sampleService: SampleService) {
this.loginForm = new ControlGroup({
email: new Control("", Validators.required),
password: new Control("", Validators.required)
});
}
doLogin(event) {
this._sampleService.login()
.subscribe(
data => /*this.countries = data,
error => this.error = "Region " + this.region + " is invalid."*/
{
this.countries = data;
});
}
}
这也是多余和不必要的
constructor(private _sampleService: SampleService){
this._sampleService = _sampleService;
}
如果将private
或public
添加到构造函数参数,则已声明实例属性并为其分配值
constructor(private _sampleService: SampleService){
// this._sampleService = _sampleService;
}
注释掉的行会抛出,因为没有_sampleService
变量,只有this._sampleSrevice
。