Created
June 3, 2019 02:26
-
-
Save lllyin/0e3218b7fae714e74573f14292866f88 to your computer and use it in GitHub Desktop.
rxjs之ajax
This file contains hidden or 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
import { ajax } from 'rxjs/ajax'; | |
import { map, tap, catchError } from 'rxjs/operators'; | |
import { Subject, of } from 'rxjs'; | |
function request(url){ | |
const subject = new Subject<any>(); | |
setTimeout(() => { | |
if(localStorage.getItem(url)){ | |
console.log('localStorage.getItem(url)'); | |
subject.next(JSON.parse(localStorage.getItem(url))); | |
} | |
}, 0) | |
ajax(url).pipe( | |
tap(userResponse => { | |
// console.log('userResponse', userResponse); | |
subject.next(userResponse); | |
localStorage.setItem(url, JSON.stringify(userResponse)); | |
}), | |
catchError(error => { | |
// console.log('error: ', error); | |
subject.next(error); | |
return of(error); | |
}) | |
).subscribe(); | |
return subject; | |
} | |
const obs$ = request(`https://api.github.com/users?per_page=5`); | |
const obs2$ = request(`https://api.github.com/users?per_page=1`); | |
obs$.subscribe(data => { | |
console.log('main1', data) | |
}) | |
// obs2$.subscribe(data => { | |
// console.log('main2', data) | |
// }) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment