Angular 6-Ionic-使用拦截器中断http请求并返回json

时间:2018-06-27 15:21:02

标签: angular typescript ionic3 observable angular-http-interceptors

如何使用HttpInterceptor中断httpRequest并返回数据(在这种情况下为json)?

在用于添加http标头的代码下面,我想如果debug为true,则中断http请求并返回JSON。

export class PostRequestInterceptor implements HttpInterceptor {

//FakeResponse is a class which return JSON data passing type
fakeResponse:FakeResponse = new FakeResponse();

debug:boolean = false;

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if(this.debug){
        let jsonFakeResponse = this.fakeResponse.faker("ticket");
        // return the json jsonFakeResponse
    }else{
        const changedReq = req.clone({headers: req.headers.set('Content-Type', 'application/x-www-form-urlencoded'),withCredentials:true});
        return next.handle(changedReq);
    }

}

}

我知道我应该返回一个可观察的(ofc),但如何返回已解决的它呢?

谢谢!

1 个答案:

答案 0 :(得分:0)

如果有人需要,我找到了解决方案。由于Http请求等待HttpResponseEvent,因此我们必须创建一个对象HttpResponseEvent并对其进行解析(带有承诺)。

export class PostRequestInterceptor implements HttpInterceptor {

//FakeResponse is a class which return JSON data passing type
fakeResponse:FakeResponse = new FakeResponse();

debug:boolean = true;

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if(this.debug){



        //retrive jsonData from 
        let jsonDummyData = this.fakeResponse.select(req.body.params.Stmt);

        //Add header for content type
        const headers = new HttpHeaders();
        headers.set("Content-Type","application/json");

        return from(new Promise(resolve => 
            //wait 300 ms to simulate internet latency 
            setTimeout( () => {
                resolve(new HttpResponse({
                    body: jsonDummyData,
                    headers: headers
                }));
            },300) 
        ));

    }else{
        const changedReq = req.clone({headers: req.headers.set('Content-Type', 'application/x-www-form-urlencoded'),withCredentials:true});
        return next.handle(changedReq);
    }

 }

}

删除next.handle语句将中断请求。