so im new on TypeScript and i need your guys help. im trying to build a module with typescript that does api calls that im later adding to my main project. so i was doing first with get requests with ajax. But i got this:
(node:1588) UnhandledPromiseRejectionWarning: TypeError: $.ajax is not a function
This is my Typescript File:
import * as $ from 'jquery'
class RedditJuice {
afterbeforeStorage:Array<string>;
totalPage:number
currentPage:number
constructor() {
this.afterbeforeStorage = []
this.totalPage = 0
this.currentPage = 0
}
fetchRedditFeed = async (afterTag:string, beforeTag:string) => {
return new Promise<JSON>((resolve, reject) => {
console.log("yey")
if(afterTag == null || undefined || "" && beforeTag == null || undefined || ""){
var url:string = "https://reddit.com/.json"
}
else if(beforeTag != null|| undefined || ""){
var url:string = "https://reddit.com/.json?after=" afterTag
}
else {
var url:string = "https://reddit.com/.json?after=" afterTag "?before=" beforeTag
}
$.ajax({
url: url,
type: "GET",
success: function(getData){
console.log(getData.data)
resolve(getData.data)
},
error: function(err){
reject(err)
}
})
})
}
fetchPostComments = async (permalink:string) => {
return new Promise<JSON>((resolve, reject) => {
var comment_fetch_url = "https://reddit.com" permalink '.json?limit=10'
$.ajax({
type: "GET",
url: comment_fetch_url,
success: function(data) {
resolve(data[1].data)
},
error: function(err){
reject(err)
}
})
})
}
}
const rApi = new RedditJuice()
console.log(rApi.fetchRedditFeed("", ""))
On the buttom of the file im trying to use the class but then i get the mentioned error... And yes im running the .js file that is compiled by tsc. I also ofc installed jQuery with npm (@types/jquery)
Thanks for your support ^____^
CodePudding user response:
Are you executing this in a browser or in the nodejs vm either as a test or directly? jquery uses the XMLHttpRequest supplied by the browser environment to implement its ajax functionality and when it is unavailable it won't work.