使用typescript访问导入的服务时出现Angular2错误

时间:2016-04-28 09:22:37

标签: javascript typescript angular

我正在尝试创建一个表单,用户将填写所需的详细信息,然后进行服务器调用并保存所需的详细信息。但无论我做什么,我都会收到这个错误。ORIGINAL EXCEPTION: TypeError: this.postService is undefined  我的主要 app.component.ts 的代码是:

/// <reference path="../typings/tsd.d.ts" />
import {Component} from 'angular2/core';
import {HTTP_PROVIDERS} from 'angular2/http';
import {ControlGroup, Control, Validators, FormBuilder} from 
'angular2/common';
import {PostService} from './post.service'

@Component({
selector: 'my-app',
template:`

<form [ngFormModel]="form" (ngSubmit)="signup()">

<div class="form-group has-error has-feedback">  <div class="input-group">

            <input type="text" id="email_id" type="text" 
ngControl = "email_id" #email_id="ngForm" value = email_id >

        </div>  </div>
<div class="form-group has-error has-feedback"> <div class="input-group">

            <input type="password" id="password" type="text" 
ngControl = "password" #password="ngForm" value = password>

 </div>  </div>

<button class="btn btn-primary" type="submit">Sign Up</button>
</form>
`,
providers:[PostService, HTTP_PROVIDERS]


})

export class AppComponent {

form: ControlGroup;
postService:PostService;
constructor(fb: FormBuilder){
        this.form = fb.group({
            email_id: ['',Validators.required],
            password: ['',Validators.required]
        });     
}
signup(){
this.postService.createPost({ email: this.form.value.email_id,
 password: this.form.value.password });

}
}

我之前尝试过'postService:PostService in the constructor but then also I was getting the same error that postService`是一个未经分类的。

post.service.ts 代码如下:

import {Http} from 'angular2/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import {Injectable} from 'angular2/core'
import {Post} from './post';
import {Observable} from 'rxjs/Observable';


@Injectable()
export class PostService {
//dependency injection
private _url = "http:127.0.0.1/accounts/login_user/";
constructor(private _http:Http) {

}


createPost(post:Post){

    return this._http.post(this._url,JSON.stringify(post))
    .map(res=>res.json());
}
}

如何解决此问题并成功将数据从表单发送到服务器并显示响应。有人可以帮帮我吗?

谢谢。

2 个答案:

答案 0 :(得分:1)

您需要将其注入您的组件:

export class AppComponent {
  form: ControlGroup;

  constructor(fb: FormBuilder, private postService:PostService){ <----
    (...)
  }

  (...)
}

不要忘记在组件的提供程序中指定此服务:

@Component({
  providers: [ PostService ] 
})
export class AppComponent {
  (...)
}

或引导主要组件时。

bootstrap(AppComponent, [ PostService ]);

答案 1 :(得分:0)

AppComponent中需要注入服务:

constructor(fb: FormBuilder, this postService:PostService){