使用HTTP observable在Angularjs 2中发布数据

时间:2017-01-15 09:00:20

标签: http angular rxjs observable

我正在使用HTTP observable进行POST请求,并且没有发出请求,我没有收到任何错误,我有一个服务定义了我用来发出请求的方法

@Injectable()
export class MovingCompanyService {
constructor(private http: Http){}

registerCompany (body: Object): Observable<RegistrationDetailsModel> {
let bodyString = JSON.stringify(body); // Stringify payload
let headers      = new Headers({ 'Content-Type': 'application/json' }); //      ... Set content type to JSON
let options       = new RequestOptions({ headers: headers }); // Create a   request option

return this.http.post("/moving_company/registration_form_2", body, options) // ...using post request
                    .map((res:Response) => res.json()) // ...and calling     .json() on the response to return data
                    .catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}   

}

我有调用此服务方法的组件

constructor(private router: Router, private moving_company_service: MovingCompanyService) {}
ngOnInit(): void {
    if( Session.has("reg_frm_1")) {
        let frm1Data = Session.get("reg_frm_1");
        console.log("Received data from form 1 ", frm1Data);
    }
}

registerCompany(): void {
    let registrationOperation:Observable<RegistrationDetailsModel>;
    let registration_details = {
        reg_frm_1: Session.get("reg_frm_1"),
        reg_frm_2: this.model
    }
     this.moving_company_service.registerCompany(registration_details)
}

我在视图点击事件(如

)上调用组件方法'registerCompany'
<button (click)="registerCompany()">Submit</button>

我不确定我错过了什么或做错了什么,我已经导入了rxjs库,地图和捕获操作符并按照所有相关导入,我将不胜感激

1 个答案:

答案 0 :(得分:1)

试试这个

        this.moving_company_service.registerCompany
          ((registration_details).subscribe(
            r =>  r,
            error => this.errorMessage = <any>error,
            () => {  });