Angular2如何使用服务类POST数据

时间:2016-05-29 02:30:05

标签: web-services rest http angular

我有一个简单的申请表,我试图发布到服务器。我是Angular2的新手

如何将数据从组件传递到服务并传递到服务器以获取POST请求。

当我直接从FireFox插件' httpRequester'直接尝试时,POST工作正常。

这是TaskComponent.ts

@Component({
    selector: 'tasks',
    template: `<div mdl class="mdl-grid demo-content">

          <div class="demo-graphs mdl-shadow--2dp mdl-color--white mdl-cell mdl-cell--8-col">
                <h3>Create Task Page</h3>   

                <form action="#" (ngSubmit)="onSubmit()">
                  <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
                    <input class="mdl-textfield__input" type="text" pattern="[A-Z,a-z]*" id="taskname" [(ngModel)]="data.taskname"/>
                    <label class="mdl-textfield__label" for="taskname">Task Name</label>
                    <span class="mdl-textfield__error">Only alphabet and no spaces, please!</span>
                   </div> 
                  <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" type="submit">Create Task</button>
                </form>          
    `,
    directives: [ROUTER_DIRECTIVES, MDL]
})

export class CreateTaskComponent {

    data: any

    constructor() { 
      this.data = {
        //taskname: 'Example Task'
      };
    }

    onSubmit(form) {
      console.log(this.data.taskname);    <--Data is passed upon submit onto the console. Works fine.  

      //Need to call the postApartment method of ApartmentService     
    }
}    

ApartmentService.ts

import {Http, Response} from 'angular2/http'
import {Injectable} from 'angular2/core'
import 'rxjs/add/operator/map';

@Injectable()
export class ApartmentService {

    http: Http;
    constructor(http: Http) {
        this.http = http;
    }

    getEntries() {
        return this.http.get('./api/apartments').map((res: Response) => res.json());
    }

    getProfile(userEmail :string){
       return this.http.get(`./api/apartments/getprofile/${userEmail}`).map((res: Response) => res.json());
    }

    postApartment(){
        // Not familiar with the syntax here
    } 
}

Server.ts

router.route('/api/apartments')          
    .post(function(req, res) {        
        var apartment = new Apartment();
        apartment.name = req.body.name;

        apartment.save(function(err) {
            if (err)
                res.send(err);
            res.json({ message: 'Apartment created!' });
        });
  })

2 个答案:

答案 0 :(得分:0)

您可以通过依赖注入注入服务并在组件中使用它

export class CreateTaskComponent {
    constructor(){private _apartmentService: ApartmentService}{}
}

您可以通过

在任何组件功能中访问它
onSubmit(form) {
  console.log(this.data.taskname);    <--Data is passed upon submit onto the console. Works fine.  

  //Need to call the postApartment method of ApartmentService     
  this._apartmentService.postApartment()
}

当引导组件时,您必须通过

将其添加为依赖项
bootstrap(AppComponent, [ApartmentService]);

执行最后一步的另一个选择是在组件装饰器中添加提供程序,如

@Component{
  providers: [ApartmentService]
}

答案 1 :(得分:0)

在组件中注入apartmentService,不需要提供者,因为我已经引导它。 (如果您启动该服务,请不要将其包含在提供程序中。它会破坏系统)

export class CreateTaskComponent {

    data: any

    constructor(private apartmentService: ApartmentService) { 
      this.data = {};
    }

    onSubmit(form) {
      this.apartmentService.postApartment(this.data);           
    }
}    

关键部分是服务中的postApartment()方法

 postApartment(data :any){
          return this.http.post('/api/apartments',
               JSON.stringify(data),{headers : new Headers({'Content-Type':'application/json'})
               })
               .map((res: Response) => res.json()).subscribe();
    } 

还要确保在server.js代码中,mongoose字段与传递的http body参数匹配。 我不得不修复它以使其工作。