Home > other >  How to simulate a get call using rxjs
How to simulate a get call using rxjs

Time:03-21

I want to simulate a get response, but without actually making httpClient.get call, in angular. I tried piping setInterval, and interval, but none work, since this is not the correct path to follow. The setInterval is not considered to obligatory return anything, so angular complains. Also the interval() method is a generator of many values of observable, so also not what I would want. I just need one call. How would I simulate a get response as observable? This is the code in the calling code (the code that calls the observable piping process):

this.order.pipe(

      tap((order) => {
        console.log('order for user', order.id);
      }),
      map((a) => {
        return this.durumService.makeDurum();
      }),
      mergeMap((o) => {
        return o;

      })
    ).subscribe(() => console.log);

This is the method in the servicethat I want to adjust to only make a fake get call (but I am still not successful):

makeDurum(): Observable<number> {
    setInterval(() => {
      return of(7);
    }, 1000);
  }

CodePudding user response:

I would suggest using any mock API to simulate requests. The bonus is that you can actually configure to return some data which lets you test even further with all the header and content goodies that you would expect from a normal http request.

E.g https://mockapi.io/docs

But anyway, looking at your example something like this would also work:

type Post = { title: string, content: string };

import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';

const post:Observable<Post> = of( {title: 'Simulating HTTP Requsts', content: 'This is off the hook!!'}).pipe(delay(2000));

post.subscribe(console.log);

Example: https://stackblitz.com/edit/typescript-rxjs-request-simulation-vjvu6l?file=index.ts

  • Related