【问题标题】:Angular 6 - Ionic - Break http request with interceptor and return jsonAngular 6 - Ionic - 使用拦截器中断 http 请求并返回 json
【发布时间】:2018-12-06 13:31:49
【问题描述】:

如何使用 HttpInterceptor 中断 httpRequest 并返回数据(在本例中为 json)?

在我用于添加 http 标头的代码下方,如果调试为真,我想中断 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);
    }

}

}

我知道我应该返回一个 observable (ofc) 但是如何返回它已经解决了?

谢谢!

【问题讨论】:

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


    【解决方案1】:

    如果有人需要,我找到了解决方案。由于 Http 请求等待一个 HttpResponseEvent,我们必须创建一个对象 HttpResponseEvent 并解决它(通过一个 promise)。

    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 语句将中断请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      • 2019-07-16
      • 2020-03-14
      • 2016-06-18
      相关资源
      最近更新 更多