在http get上检测404并快速处理它

时间:2017-12-08 08:53:43

标签: angular

我收到了这个HTTP get请求:

r1-r3

如果缺少URL,并且您已经在dev工具console.log上收到了this.httpService.getData ('http://example.com/wp-json/wp/v2/' + 'badReferenceHere').subscribe( (response: Response) => { let apiResponse = JSON.parse(JSON.stringify(response)); this.post_content = apiResponse.content.rendered; // do something with the this.post_content }, (error: any) => { this.post_content = 'An error has occurred.'; }); 消息,但是,您的代码仍显示微调器,您应该怎么做才能快速检测到并停止等待并处理404以说出诸如“该链接不存在”之类的消息?

2 个答案:

答案 0 :(得分:1)

GetMethod(url): Observable<any> {
        return this._http.get(url, { body: "" })
            .map(res => <any>res.json());
    }

答案 1 :(得分:1)

您需要在错误处理程序中处理此问题:

this.httpService.getData ('http://example.com/wp-json/wp/v2/' + 'badReferenceHere').subscribe(
      (response: Response) => {
        let apiResponse = JSON.parse(JSON.stringify(response));
        this.post_content = apiResponse.content.rendered;
        // do something with the this.post_content
      },
      (error: any) => {
        this.post_content = 'An error has occurred: ' + error.message ;
        alert(this.post_content);
        //Code to stop spinner
    });