I cannot figure out how to use WebSocketSubjects in rxjs v6.x
Here's the working HTML/JS for v5.5.6. The commented out code is my attempt at getting it working in v6.x:
<html>
<head>
<!-- <script src="https://unpkg.com/#reactivex/rxjs#6.0.0/dist/global/rxjs.umd.js"></script> -->
<script src="https://unpkg.com/#reactivex/rxjs#5.5.6/dist/global/Rx.js"></script>
<script>
// const { WebSocketSubject } = rxjs.webSocket;
// const socket$ = WebSocketSubject.create('ws://localhost:8080');
const socket$ = Rx.Observable.webSocket('ws://localhost:8080');
socket$.subscribe(
(data) => console.log(data),
(err) => console.error(err),
() => console.warn('Completed!')
);
socket$.next(JSON.stringify({
event: 'events',
data: 'test',
}));
console.log('here')
</script>
</head>
<body></body>
</html>
I got it working with rxjs#6.1.0. As I suspected, I was just using the version 6 syntax wrong. See working example:
<html>
<head>
<script src="https://unpkg.com/#reactivex/rxjs#6.1.0/dist/global/rxjs.umd.js"></script>
<script>
const { WebSocketSubject } = rxjs.webSocket;
const socket$ = new WebSocketSubject('ws://localhost:8080');
socket$.subscribe(
(data) => console.log(data),
(err) => console.error(err),
() => console.warn('Completed!')
);
socket$.next({
event: 'events',
data: 'test',
});
console.log('here')
</script>
</head>
<body></body>
</html>
Related
I have successfully fetched data from API. The fetched data shows in the alert function. However, the properties in the data function such as - 'Recovered' is not updating. I can show the fetched data using Vanilla JS. But I want to update them automatically and want to show them like this {{Recovered}}.
How can I do it??
<template>
<div class="container">
<h2>Total Recovered: {{Recovered}}</h2>
</div>
</template>
<script>
import axios from 'axios'
export default {
name:'CoronaStatus',
data: function () {
return {
Recovered: '',
TotalConfirmed: '',
TotalDeaths: '',
// test: '30',
// test_2: 'maheeb',
// componentKey: 0,
}
},
mounted(){
this.globalStatus();
},
methods:{
globalStatus: function(){
// const self = this;
// this.componentKey += 1;
axios.get('https://api.covid19api.com/summary')
.then((response) => {
// this.recovered = response.data.Global.NewConfirmed;
this.Recovered= response.data.Global.TotalRecovered;
alert(this.Recovered);
// document.getElementById('test_5').innerHTML = "total: " + this.TotalRecovered;
}).catch(err=> console.log(err));
},
}
}
</script>
<style scoped>
</style>
The easiest solution would be to refetch the information every hour with setInterval.
The best solution would be to use the WebHook provided by covid19api.com.
Vue.config.devtools = false;
Vue.config.productionTip = false;
var app = new Vue({
el: '#app',
data: {
Recovered: "Loading ..."
},
mounted() {
setInterval(() => {
this.globalStatus();
}, 3600000); // Call globalStatus every hour
this.globalStatus();
},
methods: {
globalStatus: function() {
axios
.get("https://api.covid19api.com/summary")
.then(response => {
this.Recovered = response.data.Global.TotalRecovered;
})
.catch(err => console.log(err));
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<div id="app">
<h2>Total Recovered: {{ Recovered }}</h2>
</div>
I'd like to load Vue Component via AJAX dynamically and render its template.
Main Vue Instance:
const router = new VueRouter({
path: '/vue/actions/',
mode: 'history'
});
var app = new Vue({
el: '#mainContainer',
router,
data: {
mainContent: ''
},
methods: {
action: function (url) {
alert(url);
this.$router.push({ path: '/vue/actions/?'+url});
console.log(this.$route.query);
},
actions: function () {
var action;
if (!this.$route.query.action || this.$route.query.action == 'main') {
action = 'index';
} else {
action = this.$route.query.action;
}
var mainContent;
fetch('/vue/actions/?content_type=json&action='+action).then((response) => {
if(response.ok) {
return response.json();
}
throw new Error('Network response was not ok');
}).then((json) => {
this.$router.push({ path: '/vue/actions/', query: { action: json.action }});
// this.mainContent = json.template;
console.log(json.template);
this.dynamicComponent = json.template;
}).catch((error) => {
console.log(error);
});
}
},
created: function () {
this.actions();
}
})
Initial Page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="" />
<meta name="author" content="" />
<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>
<script type="text/javascript" src="/js/vue.min.js"></script>
<script src="/js/vue-router.js"></script>
</head>
<body>
<template><div><component :is="dynamicComponent"></component></div></template>
<div id="mainContainer" v-html="mainContent"></div>
<script type="text/javascript" src="/js/main.js"></script>
</body>
</html>
Component I'd like to load via AJAX:
Vue.component('dynamicComponent', {
template: '<div>Dynamic Component!</div>'
});
Is it possible to load such Vue Componet and render its template (with an ability to use Vue data bindings in the Component template)?
Here is how I got what I need:
Main Vue Instance:
const router = new VueRouter({
path: '/vue/actions/',
mode: 'history'
});
var app = new Vue({
el: '#mainContainer',
router,
data: {
mainContent: ''
},
methods: {
action: function (url) {
this.$router.push({ path: '/vue/actions/?'+url});
console.log(this.$route.query);
},
actions: function () {
var action;
if (!this.$route.query.action || this.$route.query.action == 'main') {
action = 'index';
} else {
action = this.$route.query.action;
}
Vue.component('dynamic-component', (resolve) => {
import('/vue/actions/?content_type=javascript&action='+action).then((component) => {
resolve(component.default);
});
});
}
},
created: function () {
this.actions();
}
})
Main/Initial Page Body:
<body>
<div id="mainContainer">
<dynamic-component></dynamic-component>
</div>
<script type="text/javascript" src="{{.__web_root_folder}}/js/main.js"></script>
</body>
Component code that I'm loading when needed:
export default {
template: '<div>Async Component! {{.test}}</div>',
data () {
return {
test: 'Works!'
}
}
}
Thanks to #MazinoSUkah !
I'm starting to work with vuejs and I'm trying to make a http get call without sucess. I've tried several example showing how to do that but I get the following error in my console: this.$http is undefined.
html
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.21/css/uikit.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.21/js/uikit.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.21/js/uikit-icons.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.19.1/vis.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.19.1/vis.min.css" rel="stylesheet" type="text/css"/>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
<p v-bind:title='message'>
{{ message }}
<p>
<button v-on:click='changeView("matrice")'>get data</button>
</div>
</body>
<script type="text/javascript" src="/front/lala_web/matrice.js"></script>
</html>
js
var app = new Vue({
el: '#app',
data: {
message: 'Empty data'
},
methods:{
changeView: function(v){
this.$http.get('/view/'+v)
.then(function(resp){
this.message = resp.data;
})
.catch(function(){alert('Error')});
}
}
})
I'been able to get a http get call working using the following js, but doing so doesn't change data.message value of vuejs and I get the following error data is not defined.
js
var app = new Vue({
el: '#app',
data: {
message: 'Empty data'
},
methods:{
changeView: function(v){
var viewUrl = '/view/'
$.ajax({
url: viewUrl+v,
method: 'GET',
success: function (resp) {
if (resp.error == false){
console.log(resp)
data.message = resp.data
}
},
error: function (error) {
console.log(error)
}
});
}
}
})
You need to reference this.message not data.message. Also, you'll need to save a reference to this outside the scope of the ajax call, since this in the success handler doesn't refer to the Vue instance:
changeView: function(v){
var viewUrl = '/view/'
var self = this;
$.ajax({
url: viewUrl+v,
method: 'GET',
success: function (resp) {
if (resp.error == false){
console.log(resp)
self.message = resp.data
}
},
error: function (error) {
console.log(error)
}
});
}
Here I wrote A code which fetches data from API http://fcctop100.herokuapp.com/api/fccusers/top/recent and displays on console for starter but I'm Getting Error Like "parsererror" "Error: jQuery21106393266040831804_1456914722748 was not called"
var App = React.createClass({
//setting up initial state
getInitialState:function(){
return{
data:[]
};
},
componentDidMount(){
this.getDataFromServer('http://fcctop100.herokuapp.com/api/fccusers/top/recent');
},
//showResult Method
showResult:function(response){
console.log(response);
this.setState({
data:response.results
});
},
//making ajax call to get data from server
getDataFromServer:function(URL){
$.ajax({
type:"GET",
dataType:"jsonp",
url:URL,
success: function(response) {
this.showResult(response);
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render:function(){
return(
<div>
<Result />
</div>
);
}
});
var Result = React.createClass({
render:function(){
return(
<div>
<ul>
<ResultItem/>
</ul>
</div>
);
}
});
var ResultItem = React.createClass({
render:function(){
return(
<div>
<li>Hello This Is From ResultItem Component</li>
</div>
);
}
});
ReactDOM.render(
<App />,
document.querySelector("#app")
);
<!DOCTYPE html>
<head>
<meta charset="UTF-8" />
<title>React Tutorial</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<div id="app"></div>
<script src="demo.js" type="text/babel"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js"></script>
</body>
</html>
Your API returns JSON, you don't need use JSONP, just change dataType from jsonp to json
$.ajax({
type: "GET",
dataType: "json",
....
});
and in showResult set only response because response contains Array of Objects and does not have results property
this.setState({
data: response
});
Example
I have following Kendo.mvc grid
#Html.HiddenFor(model => model.BarCode)
<div style="padding-left:10%;padding-top:2%">
#(Html.Kendo().Grid(Model.BarCodes)
.Name("grid")
.Columns(columns =>
{
columns.Bound(e => e.DocumentSetName)
.Width(100)
.Title("Reference No");
columns.Bound(e => e.ScannedDate)
.Title("Scanning Date")
.Width(100);
})
.Sortable()
.Pageable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(3)
//.Read(read => read.Action("SearchUnregisteredIncomings", "Correspondence").Data("getSearchCriteria"))
)
.ClientDetailTemplateId("template")
)
and this is the ajax call I have made
$.getJSON('#Url.Action("Search")', {ReferenceNumber:'123'
}, function (data, status) {
var grid = $("#grid").data("kendoGrid");
grid.dataSource.data(data);
grid.refresh();
$("#loading").stop().fadeOut('fast');
});
The grid variable is undefined.
The following is the names and sequence of .js files and scripts that are loaded in _Layout.cshtml file.
<script src="/Scripts/modernizr-2.6.2.js"></script>
<script src="/Scripts/kendo/jquery.min.js"></script>
<script src="/Scripts/spin.js"></script>
<script src="/Scripts/kendo/kendo.all.min.js"></script>
<script src="/Scripts/bootstrap-multiselect.js"></script>
<script src="/Scripts/kendo/kendo.aspnetmvc.min.js"></script>
<script src="/Scripts/chosen.jquery.min.js"></script>
And the below scripts loaded after #RenderBody() section but before </body> tag
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/jquery-1.8.2.js"></script>
<script src="/Scripts/bootstrap.js"></script>
<script src="/Scripts/respond.js"></script>
<script src="/Scripts/spcontext.js"></script>
<script src="/Content/vendors/jquery-1.9.1.js"></script>
<script src="/Content/vendors/modernizr-2.6.2-respond-1.1.0.min.js">/script>
<script src="/Content/vendors/jquery.uniform.min.js"></script>
<script src="/Content/vendors/chosen.jquery.min.js"></script>
<script src="/Content/vendors/bootstrap-datepicker.js"></script>
<script src="/Content/vendors/wysiwyg/wysihtml5-0.3.0.js"></script>
<script src="/Content/vendors/wysiwyg/bootstrap-wysihtml5.js"></script>
<script src="/Content/vendors/wizard/jquery.bootstrap.wizard.min.js"></script>
<script src="/Content/assets/treeview.js"></script>
<script src="/Content/assets/form-validation.js"></script>
<script>
$(function () {
$(".datepicker").datepicker();
$(".uniform_on").uniform();
$(".chzn-select").chosen();
$('.textarea').wysihtml5();
});
(function (window, undefined) {
var $ = window.jQuery;
var document = window.document;
$(document).ready(function () {
//some code here
});
})(window);
I think the problem is due to the sequence of .js files but can not figure it out.