0

I'm looking for a way to have mock data in a CONST or in a .json file when I'm not working without my backend services or network.

For the moment I use my services :

get_clubs(): Observable<Club[]> {
    return this.http.get(`${this.config.apiEndpoint}clubs`, options)
        .map((res: Response) => res.json())
        .catch((error: any) => 'doing stuff';
};

The ${this.config.apiEndpoint} is my URL defined in my app.config.ts as a global constant (found here)

And I started to create some CONST files (user.mock.ts) :

export const CLUBS: Club[] = [
    {
        "_id": "...",
        "name": "..."
    },
    {
        ...
    }
];

Sometimes I can't reach my backend and I want to pick data from my CONST or my .json files.

Do you have any clues about that ?

Community
  • 1
  • 1

1 Answers1

0

You can use Observable.of to create an observable from a plain array:

import { CLUBS } from "./user.mock";

get_clubs(): Observable <Club[]> {
    // You can probably switch between real call and the mocked call below using a config
    return Observable.of(CLUBS);
};
Saravana
  • 37,852
  • 18
  • 100
  • 108
  • Thanks for the `Observable.of`and the tips. I still have to do a if/else statement to catch if i'm with or without the backend but it help me a lot – Normand Julian May 17 '17 at 07:05
  • Another tip: if you use something like [Fiddler](http://www.telerik.com/fiddler) you can mock the responses via Fiddler and you can leave your code as it is. – Saravana May 17 '17 at 07:19