我有一个节点js服务器端演示类型应用程序。我是通过复数视频来完成教程。并使用Typescript和 rxjs 进行反应式编程。
在我尝试使用按钮链接click事件并在客户端显示json对象之前,它工作正常。我会发布代码。请有人告诉我它为什么不起作用。
main.ts
import {Observable} from "rxjs";
let output=document.getElementById('output');
let button=document.getElementById('button');
let click=Observable.fromEvent(button,"click");
function LoadMovies(url:string){
let xhr=new XMLHttpRequest();
xhr.addEventListener("LoadMovies",()=>{
console.log("yeah");//this is for debugging, and I noticed that this line is never execute so the below lines to put movies to the client site doesnt work either.
let movies=JSON.parse(xhr.responseText);
movies.forEach(m => {
let div=document.createElement("div");
div.innerText=m.title;
output.appendChild(div);
});
})
xhr.open("GET",url);
xhr.send();
}
click.subscribe(
e=> LoadMovies("movies.json"),
e => console.log(`error: ${e}`),
() => console.log("complete")
);
movies.json
[
{
"title": "Star Wars"
},
{
"title": "Star Trek"
},
{
"title": "Starship Troopers"
}
]
的index.html
<html>
<head>
<title>RxJs</title>
<style>
#circle {
width: 20px;
height: 20px;
border-radius: 50%;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<button id="button">Get Movies</button>
<div id="output"></div>
<script src="app.js"></script>// this is actually the entry point of the app which links to main.ts code and it works just fine.
</body>
</html>
答案 0 :(得分:1)
addEventListener
的正确事件名称必须为此处指定的load
或onload
:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest