使用JSON文件的angular2设置模拟环境 [英] angular2 setup mock environment using JSON file

查看:141
本文介绍了使用JSON文件的angular2设置模拟环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立一个模拟环境,如下所示,该环境受

I am trying to set up a mock environments as follows inspired by this.

environment.mock.ts

export const environment = {
  production: false,
  PRODUCT_LIST : 'http://localhost:4200/app/mock-json/products.json',
  SAVE_CART : 'http://localhost:4200/app/mock-json/cart.json'
};

environment.ts

export const environment = {
  production: false,
  PRODUCT_LIST : 'http://x.x.x.x:9000/service/products',
  SAVE_CART : 'http://x.x.x.x:9000/service/cart'
};

服务方法

getCartData (request: string):Promise<Cart[]>{
    return this.http.post(environment.SAVE_CART, request)
                .toPromise()
                .then(response => {
                        .....
                })
                .catch(this.handleError);
  }

虽然我使用ng serve运行,但是使用原始服务端点可以正常运行.

While I am running with ng serve then everything is running fine with original service endpoint.

但是当我使用ng serve --environment=mock时,由于POST调用,保存购物车"功能无法正常工作. (所有GET调用都工作正常)

But while I am using ng serve --environment=mock the Save Cart functionality is not working because of POST call. (All the GET call is working fine)

实际上,我需要以这种方式设置结构

Actually I need to setup the structure in such a way that,

  1. 使用ng serve.我可以切换到将使用原始服务端点的原始实现.
  2. 使用ng serve --environment=mock我可以切换到将使用JSON文件的模拟实现.
  3. 切换时,我不需要触摸任何代码.对于模拟实施,由于我的JSON文件是经过硬编码的,因此将始终提供一组预定义的数据.
  1. using ng serve. I could switch to original implementation which will use original service end points.
  2. using ng serve --environment=mock I could switch to mock implementation which will uses JSON files.
  3. At the time of switching I do not need to touch any code. For mock implementation a set of predefined data will be serve always since my JSON file is hard coded.

注意: 我已经更新了主要问题,以弄清楚我要寻找的内容. 我在 Plunker 中遇到这种错误(请检查控制台日志).但是请注意:此插件没有实现环境,因此解决该插件可能无法解决我的问题.

Note: I have updated the main question to clarify the context what I am looking for. Same kind of error I am getting in this following Plunker (Please check console log). But note: this plunker does not implements the emvironments, so solving this plunker may not solve my problem.

推荐答案

我已经能够通过以下想法弄清楚.

I have been able to figure it out with the following idea .

在使用模拟环境时,如果我们可以继承和覆盖Angular2 Http帖子 使用get方法的方法

At the time of mock environment use, if we can inherit and override Angular2 Http post method to use get method

以下是解决我的问题的代码.

Here is the following code which solve my problem.

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { RequestOptionsArgs, RequestOptions } from "@angular/http";
import { ConnectionBackend, Http, Request, Response, Headers } from "@angular/http";

@Injectable()
export class MockHttp  extends Http {

    constructor(backend: ConnectionBackend,
        defaultOptions: RequestOptions) {
        super(backend, defaultOptions);
    }

    post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
        console.log('Mock Http POST...');
        return super.get(url, options).catch(err => {
            console.log(err);
            if (err.status === 404) {
                console.log('404 error');
                return Observable.throw(err);
            }
        });
    }
}

我在AppModule中使用了以下提供程序

And I used the following provider in my AppModule

    { 
        provide: Http, 
        useFactory: (
            backend: XHRBackend,
            defaultOptions: RequestOptions) => {
                if(environment.MOCK){
                    return new MockHttp(backend, defaultOptions)
                }
                else {
                    return new Http(backend, defaultOptions);
                }
        },
        deps: [XHRBackend, RequestOptions]
    }

并以此方式介绍了新的环境变量 MOCK .

And Introduced on new environment variable MOCK as this.

export const environment = {
  production: false,
  MOCK : true,
  PRODUCT_LIST : .....
};

这篇关于使用JSON文件的angular2设置模拟环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆