How can I provide inexperienced services for development (not testing) in Angular 2?

I need a way to mock my services during development (not during testing) in Angular 2. The reason is that the REST-ful server is not reliable (changing the API without notification, unstable and hard to clean and get up again). It would be nice if I could just mock my services (which are mostly REST HTTP clients).

What is the best approach for creating false backend services in Angular 2? I get a lot of Internet results for mocking backend services regarding testing, but this context is not my use case (I am not mocking the testing, but developing it).

I used angular cli to create and raise my project, and I'm not sure if this tool will help.

I am looking for an approach such as Spring , where we can annotate components / classes using "profiles", and then it’s convenient to indicate which profile is active to enter the correct dependencies.

+4
source share
1 answer

I think the best approach to achieving your goal is to use interfaces and a service provider. I hope the following sample code can point you in the right direction:

data tables.service-interface.ts

export interface DataTablesServiceInterface {
    getHeaders(): Promise<any[]>;
    getData(query?: string, offset?: number, size?: number): Promise<any>;
}

data tables.service-provider.ts

import { Http } from '@angular/http';
import { OpaqueToken } from '@angular/core';

import { DataTablesServiceInterface } from './data-tables.service-interface';
import { DataTablesService } from './data-tables.service';
import { DataTablesMockService } from './data-tables.mock-service';

import { environment } from '../../../environments/environment';

let dataTablesServiceFactory = (http: Http) => {
    var serviceToReturn: DataTablesServiceInterface;
    if (environment.production) {
        serviceToReturn = new DataTablesService(http);
    } else {
        serviceToReturn = new DataTablesMockService();
    }
    return serviceToReturn;
};

export let dataTablesToken = new OpaqueToken('DataTablesServiceInterface');

export let dataTablesServiceProvider =
    {
        provide: dataTablesToken,
        useFactory: dataTablesServiceFactory,
        deps: [
            Http
        ]
    };

mock- , angular -cli, environment.

Edit: , . dataTablesServiceProvider . , , DI .

:

constructor(@Inject(dataTablesToken) private dataTablesService: DataTablesServiceInterface)

, Angular

+4

Source: https://habr.com/ru/post/1667762/


All Articles