没有连接服务时显示错误消息

时间:2018-01-02 10:03:09

标签: javascript angular

我正在Angular项目中工作,我从服务中获取数据。如果服务未启动或无法访问,我想显示和错误消息。

服务是:

import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';


@Injectable()
export class TkgmService {

    ws = 'http://10.30.1.242/MebProxy/Controllers/Service.asmx/';
    il;
    ilce;
    mahalle;
    ada;
    parsel;
    geomAttr;

    constructor(private http: Http) {
    }

    getIlTum() {
        if (this.il) {
            return;
        }
        const url = this.ws + 'GetirIlTum?';

        this.http.get(url).subscribe(
            res => {
                const parseString = require('xml2js').parseString;
                parseString(this.cleanResponse(res.text()), (err, result) => {
                    this.il = result.ArrayOfIL.Il;
                    this.il.sort((a, b) => {
                        a = a.Ad;
                        b = b.Ad;
                        return a < b ? -1 : a > b ? 1 : 0;
                    });
                });
            }
        );
    }

1 个答案:

答案 0 :(得分:1)

您可以使用错误回调来响应source observable给出的错误。像这样:

&#13;
&#13;
import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';


@Injectable()
export class TkgmService {

    ws = 'http://10.30.1.242/MebProxy/Controllers/Service.asmx/';
    il;
    ilce;
    mahalle;
    ada;
    parsel;
    geomAttr;

    constructor(private http: Http) {
    }

    getIlTum() {
        if (this.il) {
            return;
        }
        const url = this.ws + 'GetirIlTum?';

        this.http.get(url).subscribe(
            res => {
                const parseString = require('xml2js').parseString;
                parseString(this.cleanResponse(res.text()), (err, result) => {
                    this.il = result.ArrayOfIL.Il;
                    this.il.sort((a, b) => {
                        a = a.Ad;
                        b = b.Ad;
                        return a < b ? -1 : a > b ? 1 : 0;
                    });
                });
            },
            error => {
              // show message or something
            }
        );
    }
&#13;
&#13;
&#13;

希望这有帮助。