Http-Service接口的定义,采用响应式编程,返回的对象是一个可以订阅的流

import { Injectable } from "@angular/core";

import { Http, Headers, Response } from "@angular/http";

import { Observable } from "rxjs/Rx";

import "rxjs/add/operator/do";

import "rxjs/add/operator/map";

import { User } from "./user";

import { Config } from "../config";

@Injectable()

export class UserService {

constructor(private http: Http) {}

register(user: User) {

let headers = new Headers\(\);

headers.append\("Content-Type", "application/json"\);

return this.http.post(

  Config.apiUrl + "Users",

  JSON.stringify\({

    Username: user.email,

    Email: user.email,

    Password: user.password

  }\),

  { headers: headers }

\)

.catch\(this.handleErrors\);

}

handleErrors(error: Response) {

console.log(JSON.stringify(error.json()));

return Observable.throw(error);

}

}

在使用时,需要使用subscribe来监听,接口执行的结果,并执行对应的成功后处理和失败后处理

signUp() {

this.userService.register(this.user)

.subscribe(

() => {

alert("Your account was successfully created.");

this.toggleDisplay();

},

() => alert("Unfortunately we were unable to create your account.")

);

}

results matching ""

    No results matching ""