1

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'
};

Service Method

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

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

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. 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.

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.

5
  • your json is malformed in the plunker { "name" : "Test", "value" : "Test" } Commented Jan 13, 2017 at 13:33
  • Then how the get request is working? Commented Jan 13, 2017 at 13:35
  • It wasnt.. GET worked after rectifying it Commented Jan 13, 2017 at 13:36
  • You cannot post to a .json file... Why not use the real mockService that is shipped with Angular (MockBackend from '@angular/http/testing' ? Commented Jan 13, 2017 at 13:45
  • One thing come to my mind that at the time of mock env use if we can inherit and override Http post method to use get method? Will it help? Commented Jan 16, 2017 at 6:25

2 Answers 2

2

Your json was malformed. Check the updated plunker link.

plunker here

mymodel.json:

{
  "name" : "Test",
  "value" : "Test"
}

Inorder to do post, you have to use Mockbackend which is going to receive the post request. Check this answer

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. You are right. Though my expectation is little different. I have updated again with more information.
1

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

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);
            }
        });
    }
}

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]
    }

And Introduced on new environment variable MOCK as this.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.