0
我有一個節點js服務器端演示類型的應用程序。我通過使用pluralsight跟隨教程來製作它。並使用Typescript和rxjs進行反應式編程。RXjs按鈕點擊不gettng服務器響應
它工作得很好,直到我嘗試一個按鈕來與點擊事件鏈接並獲得一個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>
什麼是'xhr.addEventListener(「LoadMovies」...)'? 'XMLHttpRequest'類絕對不會發出任何叫'LoadMovies'的事件。也許你想用'onload'來代替。 – martin
爲了這個目的,本教程使用了名爲「load」的函數,同樣的名稱「load」也傳遞給了xhr.addEventListener,所以我認爲是因爲我爲我的函數使用了名爲「LoadMovies」的名稱,所以我將它傳遞給了eventlistener好。 – touseef
請參閱https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest並查找*「事件處理程序」*標題。 – martin