Rxjs Getting Started (8)----Create a full Web application

Source: Internet
Author: User

Up (7)

Getting Real-time Updates from Twitter
    • The second part of our plan is to make a real-time instrument for earthquakes, adding different seismic reports and information about what is happening on Earth from Twitter. To achieve this, we need to create a small node. JS program that gets the stream of tweets related earthquakes.
    • Setting up our node. JS Environment
    • Configure our node. JS program. Including RXJS, we will use two of the more important third-party modules to make our programming easier: WS and Twit. Any other similar modules should have minimal changes to the code.
    • First, create a directory for our program and install those modules (which we will use). (Note the output of the NPM command, dependent on the current version and package)
    • Client–server Communication
    • Now we are ready to build our program. Let's create a new file called Index.js, in which the Tweet_stream folder is used to load the modules we will use:
var  websocketserver =  require  ( ' ws ' ) Span class= "hljs-built_in".  Server; var  Twit =  require  ( Twit '  '); var  rx  =  require  ( ' rx ' );  
varnew‘rFhfB5hFlth0BHC7iqQkEtTyw‘‘zcrXEM1jiOdKyiFFlGYFAOo43Hsz383i0cdHYYWqBXTBoVAr1x‘‘14343133-nlxZbtLuTEwgAlaLsmfrr3D4QAoiV2fa6xXUVEwW9‘‘57Dr99wECljyyQ9tViJWz0H3obNG3V4cr5Lix9sQBXju1‘});
    • Now we can create a function, OnConnect, which will do all the search tweets and interact with the client. We can call OnConnect to initialize a websocket server once this websocket is connected and ready:
function onConnect(ws) {console.log(‘Client connected on localhost:8080‘);}varnew8080‘connection‘).subscribe(onConnect);
    • We can log in to our app and start with the websocket 8080 port:
    • This message about the client connection will not be printed because we have any browser connected to the server. Let's adjust our meter code and we'll use the Rxjs-dom fromwebsocket operator:
function initialize() {var socket = Rx.DOM.fromWebSocket(‘ws://127.0.0.1:8080‘);...
    • In the above processing code, Fromwebsocket creates a subject, which serves as a service provider that accepts and sends messages to WebSocket server, and by subscribing to the socket, we will receive any message sent to us by the server.
    • Now we can send the earthquake message sent by the server we received:
Quakes. Bufferwithcount( -). Subscribe(function (quakes) {Console. Log(quakes);var quakesdata = quakes. Map(function (Quake) {return {ID:Quake. Properties. NET+ Quake. Properties. Code,Lat:Quake. Geometry. Coordinates[1],LNG:Quake. Geometry. Coordinates[0],Mag:Quake. Properties. Mag};});? Socket. OnNext(JSON. Stringify({quakes:quakesdata}));});
    • We also create a subscriber from the server message:
socket.subscribe(function(message) {console.log(JSON.parse(message.data));});
    • Now that we reload the browser, this client message will appear on the terminal:

    • That's weird! This browser can send commands to the server when it starts receiving earthquakes from remote JSONP resources. So far, this server has completely ignored these messages. Go back to the code of our tweet stream and do something about it.

    • First, we will connect to the message event from the browser client, which arrives at the server. Whenever the client sends a message, the WebSocket server will emit a message event to connect to the messages. In this case, this content is a layered object.
    • In the OnConnect function, I write the following code:
var‘message‘).subscribe(function(quake) {JSON.parse(quake);console.log(quake);});
    • If we restart the server (ctrl-c in terminal) and reload the browser, we can see the earthquake details, these they come in will CBD AH terminal on the print. This is good, we can now search for earthquakes related to tweets.
    • Retrieving and sending Tweets
    • We are using a Twitter client based on the node. JS Twit stream to connect to Twitter and search for tweets. From now on, all the code will work inside the OnConnect function because it assumes that a connection to WebSocket has been established. Now let's initialize the tweets stream:
var stream = T.stream(‘statuses/filter‘‘earthquake‘,locations: []});
    • This tells us that the Twit instance T meets Twitter's statues stream, filtered by the earthquake's keyword. Of course, this is common and not directly related to earthquakes that are now occurring. Notice the empty locations array. It is an array of latitude and longitude, using the word earthquake to filter the tweets by their geographic location.
      It's special! Let's subscribe to this stream and start sending tweets to the browser:
‘tweet‘).subscribe(function(tweetObject) {ws.send(JSONfunction(err) {if (err) {console.log(‘There was an error sending the message‘);}});});
    • If we reboot the server and reload the browser, we receive the tweets on the browser and print the tweets on the developer's layout control.
    • These tweets are not filtered by the two seismic locations. To achieve this, we need to deal with each earthquake message received as follows:
    • Get the latitude and longitude of each earthquake center and create a restricted box that defines the location of the tweets we think are related to earthquakes.
    • Accumulate all the coordinate boxes so that the tweets are sent to the client and describe the relevant earthquakes on the map.
    • Whenever we receive news of a new earthquake, update the Twit stream with the new package.
    • The following are:
Rx.Observable.fromEvent (WS,' message '). FlatMap ( function(quakesobj){Quakesobj =JSON. Parse (quakesobj);returnRx.Observable.from (Quakesobj.quakes);})? . scan ([], function(Boundsarray, Quake) {?varbounds = [QUAKE.LNG-0.3, Quake.lat-0.15, QUAKE.LNG +0.3, Quake.lat +0.15].map ( function(coordinate) {coordinate = coordinate.tostring ();returnCoordinate.match (/\-?\d+ (\.\-?\d{2})?)[0];}); Boundsarray.concat (bounds);?returnBoundsarray.slice (Math. Max (Boundsarray.length- -,0));})? . Subscribe ( function(boundsarray) {Stream.stop (); stream.params.locations = Boundsarray.tostring (); Stream.start ();});
    • Here the above code takes place step-by-step:
    • 1: We're going to use scan again. Every time we need to accumulate results and immediately generate new values, scan is our friend. In this case, we will keep the coordinates of the earthquake in the Boundsarray array.
    • 2: From the latitude and longitude of the coordinates of a single seismic center, we create an array of regions that contain the northwest and southeast coordinates. These approximate boundaries create a rectangular box for a large city. After that, we used a regular expression to limit the accuracy of two decimal places per coordinate to follow the specifications of the Twitter API.
    • 3: We connect the resulting boundary to the Boundsarray, which contains each seismic boundary before it. After that, we take the nearest 25 pairs of boundaries (there are 50 items in this array), which is the TWITTERAPI limit.
    • 4: Since then, we subscribe to observable, in the OnNext function, we restart the current Twit stream to reload the update location, and through our new location array to filter, converted to a string.
    • After restarting the server and reloading the browser, we can receive the relevant tweets in our browser program. To the current value, we can only see the original data object in the developer console. In the next section, we will display the tweets on our instrument via HTML.
    • Showing Tweets on the Dashboard
    • Now we rushed to the server to receive tweets, only left to do is to put them on the screen display. We will create a new HTML element where we append the new tweets.
<divid="tweet_container"></div>

We will be working with our new socket observable to process the new Tweet objects and append them to the newly created Tweet_container element.

socket.map(function(message) {returnJSON.parse(message.data); }).subscribe(function(data) {var container = document.getElementById(‘tweet_container‘);container.insertBefore(makeTweetElement(data), container.firstChild);});
    • Any new tweets will appear at the top of the list, and they will be created by maketweetelement, a simple function that creates a tweet element, and positions the data we pass on to the top:
function Maketweetelement (tweetobj) {var Tweetel = document.createelement ('Div'); tweetel.classname = ' tweet '; var content = ' "$TWEETIMG" class="Avatar"/> ' + ' <Div class="Content">$text</Div> ' + ' <Div class="Time">$ Time</Div> '; var Time= new Date (tweetobj.created_at); var timetext = Time. tolocaledatestring () + "+ Time. tolocaletimestring (); content = Content.replace (' $tweetImg ', tweetObj.user.profile_image_url); content = Content.replace (' $text', Tweetobj.textContent = Content.replace (' $ Time', timetext); tweetel.innerhtml = content;returnTweetel;}
    • Finally, we use a related toolbar to locate the tweets that can give us more information about the results of the earthquake region.
Ideas for improvements
    • This instrument has already worked, but there are many improvements that can be made. Here are some of the better suggestions:
    • By adding more seismic data, the USGS is a good resource, but it is mainly offered in the United States. Earthquakes that come together all over the world will be more interesting, not just the United States, and show them on the map. In this way, you need to use merge and Mergeall to help, and use the DISTINCT option function to go heavy.
    • Whenever a user clicks on a tweet, a related earthquake is circled on the map. This will include a collation of the server's seismic tweets, and you will probably use the groupby operator to categorize tweets into a specific geographic region.

Rxjs Getting Started (8)----Create a full Web application

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.