angular2 setup mock environment using JSON file

后端 未结 2 1322
执念已碎
执念已碎 2021-01-25 04:30

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

environment.mock.ts

export const environment = {
  production: fa         


        
相关标签:
2条回答
  • 2021-01-25 04:50

    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 : .....
    };
    
    0 讨论(0)
  • 2021-01-25 04:57

    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

    0 讨论(0)
提交回复
热议问题