Skip to content

Instantly share code, notes, and snippets.

@BetterProgramming
Created May 25, 2020 14:13
Show Gist options
  • Save BetterProgramming/13095dd06793f371d434903d6834d5ee to your computer and use it in GitHub Desktop.
Save BetterProgramming/13095dd06793f371d434903d6834d5ee to your computer and use it in GitHub Desktop.
request(): Observable<any> {
return new Observable(observer => {
fetch(`${baseUrl}${this.url}`,{
method: this.method as any,
headers: this.headers,
body: this.body
}).then((r: any) => {
return r.json()
}).then((data: any) => {
observer.next(data);
observer.complete();
}).catch((e: any) => {
observer.error(e);})
});
}
@Developer1Dev
Copy link

Hi, I suppose this is a typescript code.
First time I see that
Could explain line by line what this code do ?

Thanks

@cabbage-cart
Copy link

cabbage-cart commented Nov 11, 2020

Hi, I suppose this is a typescript code.
First time I see that
Could explain line by line what this code do ?

Thanks

we first define our method by assigning a name and declaring what would be the return type of our method. In this case we're returning an Observable which represents asynchronous data streams provided by rxjs library, similar to Promises. We then create a new instance of an Observable which accepts a callback function as its' first parameter. It is in this function that we access the observer object and use the methods .next(), .complete(), and .error() to modify our data stream. The fetch method is native to Javascript and just returns a promise which we resolve here and pass the resolved data to our stream using the observer.next() method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment