Created
October 9, 2018 16:41
-
-
Save ciaranchen/838b68084b909c01de5241ec7a776b7a to your computer and use it in GitHub Desktop.
jsonp to get douabn isbn data
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
import { Injectable } from '@angular/core'; | |
import {Md5} from "md5-typescript"; | |
const remove_timeout = 20000; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class DoubanService { | |
private apiRoot = 'https://api.douban.com/v2/book'; | |
constructor() {} | |
searchISBN(isbn: string) { | |
return new Promise((resolve, reject) => { | |
let timeId; | |
const hash_str = Md5.init(isbn); | |
const callbackName = `jsonp_${hash_str}`; | |
const url = `${this.apiRoot}/isbn/${isbn}?callback=${callbackName}`; | |
const scriptElem = window.document.createElement('script'); | |
// clear all | |
const clearFunction = () => { | |
window.document.body.removeChild(scriptElem); | |
delete window[callbackName]; | |
}; | |
// sucess | |
window[callbackName] = res => { | |
resolve(res); | |
timeId = setTimeout(clearFunction, remove_timeout); | |
}; | |
// fail | |
scriptElem.onerror = () => { | |
reject(new Error(`failed to get ${url}!`)); | |
clearFunction(); | |
if (timeId) { clearTimeout(timeId); } | |
}; | |
scriptElem.id = callbackName; | |
scriptElem.src = url; | |
scriptElem.type = 'text/javascript'; | |
window.document.body.appendChild(scriptElem); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment