I'm trying to import RxJs in a small javascript project using "import" in my script file but I keep on getting the following error:
Subscriber.js:10 Uncaught (in promise) TypeError: Cannot set properties of undefined (setting 'rxjs')
This is what my html file looks like:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./styles/style.css">
<title>Load RxJs using import</title>
</head>
<body>
<h1>Importing RxJs Lib</h1>
<div>
<h1 id="info">'loading ...'</h1>
</div>
<!-- <script src="https://unpkg.com/rxjs#7.5.7/dist/bundles/rxjs.umd.js"></script> -->
<script src="./js/script.js"></script>
</body>
</html>
The script file looks like this:
// const updateUI = text => document.querySelectorAll('#info')[0].innerText = "finished";
const loadRxJsLib = async () => {
await import('https://unpkg.com/rxjs#7.5.7/dist/bundles/rxjs.umd.js');
}
document.addEventListener('DOMContentLoaded', (event) => {
loadRxJsLib();
});
document.addEventListener('readystatechange', (event) => {
if (document.readyState === 'complete') {
const { range } = rxjs;
const { filter, map } = rxjs.operators;
range(1, 200)
.pipe(
filter((x) => x % 2 === 1),
map((x) => x + x)
)
.subscribe((x) => console.log(x))
}
});
Any idea why it's not working? any comment will be highly appreciated
After researching a little bit more, I found out that it might be related to the CDN. I have tried the skypack CDN with the following URL
https://cdn.skypack.dev/pin/rxjs#v7.5.7-j3yWv9lQY9gNeD9CyX5Y/mode=imports/optimized/rxjs.js
...and I did not get the error anymore
Related
I have a simple text file in the same directory as HTML file , I used the fetch command in javascript to display the text file content in the page div section when the loading of the page finish
however, my code doesn't work and nothing has been displayed, my question is does the fetch command suitable for such a task or should I use filereader ?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Page</title>
<meta name="generator" >
<style type="text/css">
</style>
<script type="text/javascript" defer>
const myfile=location.href.slice(0,location.href.lastIndexOf("/"))+"/a.txt"
console.log(myfile);
async function getTextFile1() {
try {
const response = await fetch(myfile, { mode: 'no-cors' });
const fileText = await response.text();
//console.log(window.location);
//console.log(window.location.href);
const tagElement = document.getElementById("about_layer");
tagElement.innerText = fileText;
} catch (error) {
console.log(error);
}
}
window.onload = getTextFile1;
</script>
</head>
<body>
<div >should be placed here </div>
<div id="about_layer">
</div>
</body>
</html>
There is nothing wrong with your code , just try running your html file using development server .
You can use Live Server visual studio code extension for that.
This question already has an answer here:
Why doesn't my arrow function return a value?
(1 answer)
Closed 9 months ago.
I've been trying to figure out why my components will not display at all for the past 5 hours. Any help is greatly appreciated.
Here is the source:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/react#18/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#18/umd/react-dom.production.min.js" crossorigin></script>
<script src="modules/Container.js"></script>
<script src="modules/CategoryFolder.js"></script>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div id="root"></div>
<script>
let root = $('#root')[0];
reactroot = ReactDOM.createRoot(root);
reactroot.render(React.createElement(Container));
</script>
</body>
</html>
modules/Container.jsx:
const SPACING = 10;
class Container extends React.Component {
constructor() {
super();
this.state = {categories: []};
}
componentDidMount() {
$.ajax({
url: './items/categories',
dataType: 'json',
async: true,
success: (categories) => {
this.setState({categories});
}
})
}
render() {
this.state.categories.map((category, i, a)=>{
<CategoryFolder style={{'z-index':i,top:i*SPACING+'%'}} CategoryTitle={category}></CategoryFolder>
})
}
}
modules/CategoryFolder.jsx:
function CategoryFolder(props) {
let css_class = '';
let id = Number.parseInt(props.key) + 1;
if (id % 3 == 0)css_class = 'tert-tag';
else if (id % 3 == 2) css_class = 'even-tag';
return (
<div class="gwd-div-7ybz" name="folder-container">
<div class={"gwd-div-qb7z " + css_class} name="folder-tag-container">
<fieldset class="gwd-fieldset-poz5" name="folder-tag-text"><h1 class='category-title'>{props.CategoryTitle}</h1></fieldset>
</div>
<svg data-gwd-shape="rectangle" class="gwd-rect-c8gx" name="folder-recipe-body"></svg>
</div>
)
}
When I debug all this, the root element is identified and I can see the ajax function succeeding and the render function of Container running. But, for whatever reason, the root element remains untouched as <div id="root"></div> without ever being modified.
Thanks in advance!
Update: I should mention that the console shows no errors at all!
Update 2: The files posted are .jsx while the ones included in index.html are transpiled with npx babel --watch modules/src --out-dir public/modules --presets react-app/prod
You don't return <CategoryFolder style={{'z-index':i,top:i*SPACING+'%'}} CategoryTitle={category}></CategoryFolder> in map() function
I have a problem. I want to make page like this
https://www.idntimes.com/korea/kpop/matthew-suharsono/rekomendasi-lagu-dreamcatcher-untuk-pengantar-tidur-c1c2/5
I already can add the page number at the end of the URL. But when I'm in testing.html/4 and I want to refresh it, the page does not appear and shows the error "Cannot get testing.html/4". How to make it can refresh like usual?
Here's my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<style>
.spinner {
display: none;
}
</style>
</head>
<body style="font-size: 60px;">
<div class="news-content">
</div>
<div class="loading">
<p>Loading Please Wait</p>
</div>
<script>
function loadData(count) {
fetch('/index.json')
.then(res => res.json())
.then(json => {
if (count < json.length) {
let text = document.createElement('p');
text.innerText = json[count].text;
document.querySelector('.news-content').append(text);
if (count > 0) {
history.pushState(null, null, `/testing.html/${count}`)
}
}
});
}
let count = 0
window.addEventListener('load', loadData(count));
window.addEventListener('scroll', () => {
if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
count += 1;
loadData(count)
}
})
</script>
</body>
</html>
It seems to me that you are using pure HTML files in an HTTP/HTTPS local server. When you are having this kind of instance of the server you are not dynamically generating pages because you don't have any server side setup behind the HTML file.
You can do this using queries and since your app doesn't contain any server backend use client Javascript to create a pagination concept.
Instead of having a route type system ( which is usually handled by controller on the backend ) use query system:
Instead of:
/testing.html/{PAGE_NUMBER}
Use:
/testing.html?page={PAGE_NUMBER}
To get page query in Javascript, use the following function:
function getPageNumber() {
const urlParams = new URLSearchParams(window.location.search);
const page = urlParams.get('page');
return page;
}
Then create a function where you would paginate the data ( assuming the data is an array ):
function paginateData(data, resultsPerPage, pageNumber) {
// Chunk the data based on the limit
let result = data.reduce((rows, key, index) => (index % resultsPerPage == 0 ? rows.push([key]) : rows[rows.length-1].push(key)) && rows, []);
// Return the current page with index calculation
return result[pageNumber - 1];
}
And the final code should be something like this:
function getData(data) {
const RESULTS_PER_PAGE = 2;
const currentPageNumber = Number(getPageNumber());
const paginatedData = paginateData(data, RESULTS_PER_PAGE, currentPageNumber);
// If paginated data is undefined return first page
if (!paginatedData) {
/*
You can even redirect to /testing.html?page=1
*/
return paginateData(data, RESULTS_PER_PAGE, 1);
}
return paginatedData;
}
All you are left with is to provide the function getData with an data parameter resembling an array type.
I'm trying to realize that when I press my photo, it changes to an angel photo, and when I press celebrity photo, it changes to a ghost photo.
In VSCode, it's good when you look at copy path, but it's image (async) 404 error just by posting it on GitHub pages. Help me. Because of this, the commit is already 40.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>친구들을 위한 사이트</title>
<link rel="stylesheet" href="style.css" />
<link href="https://fonts.googleapis.com/css2?family=Gugi&display=swap" rel="stylesheet">
</head>
<body>
<h1>투표부탁해!!</h1>
<div class="container">
<div class="comment">누가 더 잘생겼나요?! 정답을 맞추면 선물이 와르르!</div>
<img src="images/제혁.png" class="image-jehyuk" onclick="changeImage()"></img>
<span>송제혁</span>
<img src="images/고수.png" class="image-gosu" onclick="changeImage2()"></img>
<span>고수</span>
</div>
<script src="index.js" defer></script>
</body>
</html>
const jehyuk = document.querySelector(".image-jehyuk");
const gosu = document.querySelector(".image-gosu");
const mainTitle = document.querySelector("h1");
const subTitle = document.querySelector(".comment");
function makeSound() {
let gosupick = new Audio("sounds/비명.mp3");
gosupick.play();
}
function thanksText() {
mainTitle.innerHTML = "감사합니다ㅎㅎ";
subTitle.innerHTML = "감사합니다ㅎㅎ";
}
function badText() {
mainTitle.innerHTML = "벌이닷!";
subTitle.innerHTML = "벌이닷!";
}
function changeImage() {
if (jehyuk.getAttribute("src") === "images/제혁.png") {
jehyuk.setAttribute("src", "images/제혁픽.png");
jehyuk.classList.add("bigger");
thanksText();
} else {
jehyuk.setAttribute("src", "images/제혁.png");
}
}
function changeImage2() {
if (gosu.getAttribute("src") === "images/고수.png") {
gosu.setAttribute("src", "images/고수픽.png");
gosu.classList.add("bigger");
badText();
} else {
gosu.setAttribute("src", "images/고수.png");
}
}
Answer
Hello, 제혁! Way I see it's just korea language encoding error
If you check "고수" === "고수" you can get false because of it is write difference encoding type (Maybe utf-8 and utf-16) So, you need to normalize your text
Korean Answer
한국어가 같게 보이는데 Javascript 특성상 인코딩 타입에 따라 글자는 같게 보이나, 서로 다른 글자로 인식하는 경우가 Mac OS(경험상) 있습니다.
콘솔로 테스트 해 본 결과 바이너리 데이터로는 "제혁픽" === "제혁픽"이 false로 나와서 없는 데이터라고 나오고 있습니다. 보통 이 문제를 해결하기 위해 String 타입에 normalize()라는 메소드를 쓸 수 있습니다.
I ask for stack overflow user's patience. I'm so sorry using our own language but it is problem about korean language encoding type.
Reference Image
I'm trying test of Electron app with Spectron.
But I can't test client window javascript global variable.
Here is my simplified code.
Please help me.
Thanks.
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>MY ELECTRON</title>
<script type="text/javascript" src="script.js"></script>
<link href="./style.css" rel="stylesheet">
</head>
<body>
</body>
</html>
script.js
let mode;
function onload_func(){
mode = 'normal';
}
window.onload = onload_func;
spec.js
const Application = require('spectron').Application
const assert = require('assert')
const electronPath = require('electron')
const path = require('path')
let app;
describe('Application launch', function () {
this.timeout(10000)
beforeEach(function () {
app = new Application({
path: electronPath,
args: [path.join(__dirname, '../src')]
})
return app.start()
})
afterEach(function () {
if (app && app.isRunning()) {
return app.stop()
}
})
it('initial mode',function(){
assert.equal(app.client.mode,'normal');
})
})
I'm not sure if it will solve your specific tests, but app.browserWindow should do the trick since as they say:
It provides you access to the current BrowserWindow and contains all
the APIs.
Note that it's an alias to require('electron').remote.getCurrentWindow()
Read more: https://github.com/electron/spectron#browserwindow