如何使用angular2 Observable

时间:2017-05-09 11:13:33

标签: angular

任何人都可以帮我解决如何在http请求中使用Observable来处理成功,失败和拒绝的情况吗?

2 个答案:

答案 0 :(得分:1)

创建服务:

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class MyService {
     constructor(private _http: Http) {
     }

     private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || "Server error");
     }

     getMethod(): Observable<any> {
        return this._http.get("yourGetUrl")
           .map((response: any) => <any>response.json())
           .catch(this.handleError);
     }

}

然后在你的组件中:

import { Component, OnInit, Injectable } from '@angular/core';
import { MyService } from '../../services/my.service';

@Component({
   selector: 'my-component',
   templateUrl: 'my-component.html',
   styleUrls: ['my-component.css'],
   moduleId: module.id,
   providers: [MyService]
})
export class MyComponent implements OnInit {
     constructor(private _myService: MyService) {
     }

     ngOnInit() {
        this._myService
           .getMethod()
           .subscribe(
              data => {//here is the data},
              error  => {//here is the error}
           );
     }
}

答案 1 :(得分:1)

应该像下面的代码:

在服务中

import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

public getData(): Observable<Type> {
  return this.http.get(request)
   .map(res:ResponseType => res.json()) //Success
   .catch(err => console.log(err)); //failure
}

在组件中:

getData().subscribe(
    data => console.log(data),
    error => console.log(error) //reject
);