0

I have an original service (in angular 5) with API that returns Observable.

I need to create similar mock service called ServiceStub. In the mock I provide this API definition (same signature as original) but reading from a local json file:

    public myAPI(): Observable<CompleObject[]> {

            const x = this.httpClient.get('..//stubs/myJsonFile.json');
            return Observable.of(x) // syntax error here
        }

so in the module where the original service is provided, I replace this line:

OriginalService

(in the providers array) by

{ provide: OriginalService, useClass: ServiceStub },

Running the app, with a small modification to myAPI() in the mock just to get it to build, I get that the original is still called instead of the mock. Despite of the previously mentioned changed to the module, where I instruct the mock to be used in all places where the original was intended.

2 Answers 2

1

Is httpClient the actual HttpClient from HttpClientModule? If so, I think you could just return x rather than of(x) since get() already returns an Observable.

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

3 Comments

Thanks Frank, now it doesn't work because x is an Observable<Object> whereas the method return type is Observable<MyCustomComplexObject[]>. A mapping must be missing? And httpClient is of type HttpClient from '@angular/common/http';
Ah, it sounds like an issue I ran into the other day actually. Try calling get by declaring the type e.g. get<CompleObject[]>('path/to/doc').
Thank you Frank I hadn't realised you posted this. It didn't work for me with get, maybe we re working with diff versions of angular or I didn't import it from the correct namespace (several suggestions had popped up) so I in the end I used require and posted that solution. Thanks a lot.
0

The problem was in teh definition of the API from the mock:

const x = <MyComplexObject[]> (require('..//stubs/myJSONFile.json'));
return Observable.of(x);

Now it works.

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.