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

查看:16
本文介绍了使用 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 中遇到了同样的错误(请检查控制台日志).但请注意:此 plunker 未实现环境,因此解决此 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 .

在mock环境使用的时候,如果我们可以继承和覆盖Angular2 Http post使用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天全站免登陆