Created
May 25, 2020 14:13
-
-
Save BetterProgramming/13095dd06793f371d434903d6834d5ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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);}) | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 theobserver.next()
method.