The Angular Blog

It’s time to start work on the Blog App project. As mentioned in previous posts my first project is to create a blog web application from scratch on both front and back end. First using the MEAN stack, then trying out different tech combinations on front and back end. I’m thinking of trying; React, Asp.Net, MySql (instead of MongoDB) and perhaps Ruby on Rails.

At this time I’ve had good experiences with MongoDB, with Node and Express and with Angular. Based on these experiences I’ve decided to start by creating the frontend Angular app before determining the design of the backend nodeExpress server and the MongoDB schematic.

The Angular Blog

I’ve worked on the Angular Blog in small increments over the past weeks. My approach was to start from scratch but to refer to the Tour of Heroes tutorial for guidance with the process. After setting up a basic project the first task was to find a way to get a text editor running as this is the crux of the application. Other tasks would be to create the different views, and to load and save blog posts from a web-api. In the remainder of this post I will describe the tasks I’ve worked on and the issues I’ve dealt with. Outlined here:

  • Quill Editor
    • Getting the styling to work.
    • Getting data into the editor.
    • Getting data out of the editor
    • Preserving the layout
  • Web-api

The current version

First a quick walkthrough of the current version.

This is the app root page. Click home will display the list of all blog posts.

Hovering a blog post will highlight it. Clicking it will route to the editor view.

As can be seen the main text is in the editor field, the title is displayed above. Pressing the delete button with delete the post and take the user back to the previous page.

Clicking the “New Post” button in the navigation bar will create a new post on the backend and take the user to the editor view for that post.

As can be seen there is no title, and no way to add a title yet.

Changing the text in the editor will automatically send those changes to the backend.

Navigating back to the home view it is seen that the new post has been added, with a new ID (as seen in the upper right corner of the post).

Finding an Editor

A quick google search for text editor modules for Angular came up with only one or two suggestions, and the main one seemed to be ngx-quill by KillerCodeMonkey on GitHub.

It is an Angular TS wrapper of QuillJS a pure Javascript version. Eventually I think I should create my own wrapper, to be able to get full value of QuillJS but for now this will get me moving.

Complications

It turns out it was not nearly as easy to get running as I hoped. The documentation from KillerCodeMonkey (KCM) is pretty sparse. I was able to install the module, but actually using it turned out more difficult. They had supplied an example that you can also download. This allowed me to look at how he had setup and got me started.

The very first issue though is that the editor is all over the place without a proper style sheet. KCM writes:

"include theme stylings: bubble.css, snow.css of quilljs in your index.html"

They don’t really mention how. At the QuillJS page I found a link to a stylesheet that I then could link to in the html. I want, however, to have the stylesheet on my server, served with the page. At first I tried to link to the style sheet in the Angular component I had created to hold the Editor.

Each component has meta information with style sheet URLs. Unfortunately, as I had to learn the hard way, stylesheets are limited to the component they are referenced in. So when I use KCMs component in my component the style I define is not transferred to his.

To solve the problem I had to include the downloaded stylesheet in the global style.css file. It’s not a glorious solution, and I bet there is a better one, but for now it will get me moving.

Getting text in and out

When editing a blog post, the text of the blogpost obviously need to be input into the editor. Inspecting the example code from KCM I found out that the editor html element has a property that is bound to a variable in the TypeScript. In this case named textFormat.

The property “format” determines how the editor should interpret the string from the textFormat variable.

We also need to know when the user has edited the text. To that effect the editor supplies an event to subscribe to.

onContentChanged is called whenever the content of the editor is changed. To avoid too many calls to the backend debounceTime() is called. It delays the call until the event has been quiet for 400ms in this case. It supplies the content of the editor as a parameter.

To preserve the format of the content; the font size, headings and so forth, I save the data in html encoding.

communicating with the backend

For now I use the same web-api as used in the Tour of Heroes tutorial. I created a blog.service that will be injected into the text editor class.

The updateBlogPost function creates a http put request passing in the blogpost. The function returns an Observable, since it’s an asynchronous call. Here I learned another hard lesson. When I first called this function it didn’t update the data in the web-api. After an hours of debugging and researching I reread the tutorial and found that i had forgotten to subscribe to the Observable. A function that returns an Observable will only fire if something subscribes to the Observable.

Conclussion

I will end this blog post here and perhaps update it later with details on how I implemented creating new posts and deleting posts. The next feature I will work on for the Angular Blog will be a login system, so only an admin can create, update and delete blog posts.

Angular 2+ and the Tour of Heroes

After getting an overview over Node JS, it’s time to start creating a frontend that will help me specify the methods the RESTful app should provide.

I had decided to try out both React and Angular, since they seem to be the most popular frontend techs. Of the two I will start with Angular.

Angular is an opensource framework developed by google it encourages the use of TypeScript, which is superset of javascript (ES6). It’s naming is slightly confusing as Angular 1.x is a quite different variation with no TypeScript. Angular 2 was the initial name for the new version of Angular, but seeing as they are soon at version 7 it seems only proper that they chose simply to refer to Angular 2+ as Angular.

Starting with Angular and TypeScript turned out to be surprisingly easy as they have a very nice and up to date tutorial at their website. It’s called Tour of Heroes, and in it you create a few different views where you can inspect a set of Heroes, change their names and add or delete them from the list. The tutorial went through everything from component creation, one and two way data-binding (to the html), through frontend routing and even showed how to use a mock-backend component to emulate having a backend.

I will go through some of the main points presented in the tutorial here:

  • Component system
  • Services and the MVC
  • Routing
  • Web-api

Component System

Angular uses a component system where each component is split into three parts. A typescript file, a html file and a css file. 

Components should in general be so minimalistic and specific as possible. To allow for maximum reuse-ability and pruning of the unused code. Components are introduced into the app via the main component, conventionally named app.component.

In a components typescript file (.ts) a selector is defined that is then used to insert the component into the html of the app.component or any nested components html.

This makes it easy to design reusable components with simple independent functionality that can be nested in other components.

To generate a component Angular provides a command line interface (CLI) that can generate a new component folder with all the files needed and registers the component in the app.module.

The app module is what boostraps the app. It also defines the app as a module. Modules are independent solutions that can be imported into other apps. The app module is where the components of the app are declared, and where other modules are imported. An important note is that the order modules are imported in is important. For instance importing the HttpClientInMemoryWebApiModule before the HttpClientModule would not work.

Services and the MVC

Angular also allows to define services that unlike components only consist of a single .ts file. It follows the naming convention name.service.ts.

Services provides a way to implement the Model, View, Controller model. Providing a separation between view and controller. The component that use a service has no idea how the services works and the service no idea what it provides a service to. This allows for more reuse and flexibility as well as easier debugging unit testing.

A service is injected into the component via the component constructor. A service could for instance be responsible for interacting with the backend, or passing messages internally in the app between components.

Routing

Angular has a whole set of modules available for use by importing them in the app.module as shown above. One of them is the AppRoutingModule. This module will intercept http requests in the browser. Routes can then be defined that will link a specific route with a specific component. This component will then be inserted into a <router-outlet/> element. In this way the app can avoid loading a new page and just load the element that is required.

 Web-api

The Tour of Heroes tutorial conveniently introduces a web-api module that can emulate a backend server and provide a response to requests sent by the services. This is super smart because it allow the full design of the client app before designing a suitable backend. Once the frontend is fleshed out the web-api module can be replaced with an actual backend service.

The web-api module use a data file and will persist data between views as long as the web app isn’t reloaded.

Conclusion

I’m quite happy with Angular, the tutorial was very informative and easy to follow. It left me feeling ready to start creating my Blog App. I like the modular component structure of Angular and the clarity it provides.

I used visual studio code as IDE and it it a real pleasure to work with.

 

Node.js, Express, and the MEAN/MERN tutorial

So previously I followed the tutorial I found at mongoDB’s webpage on how to how to create a MEAN and a MERN stack app. I read through the first parts on creating the server app and made the app work with only a few issues. The main issue being that the tutorial use mock data and requests you to generate a new mock data link. The method they suggest seems to be outdated though.

The tutorial itself also seems a bit outdated. I wanted to use the tutorial as a basis for my ‘creating a blog project’, from now on The Blog2 project. I quickly ran into issues with outdated versions, since both node, express and the mongoDB driver have new versions that work slightly differently. A further complication came from the fact that the MEAN tutorial project used PUG and Angular with typescript that needs to be compiled. So copying from the project became really complicated, without a deeper understanding of Express.

Therefore I decided it would be best to start learning Express fundamentals. Express has a generator to start off a project, but I thought it best to try and create the simplest possible version of a RESTful server app. Express use PUG formerly Jade as a default view engine and I began discovering what PUG is about. After some research it seems to me though that it’s too much of a hassle to learn PUG. The MEAN tutorial from mongoDB simply used it to serve a starting page for Angular, but even then it seems there are smarter approaches like simply have a public access folder for the angular entry point.

I created a simple app with two simple features:

A post route to /addDoc, with which to add documents to the collection. I used a CURL command to test the functionality:

echo ‘docs=[{“string”:”test”},{“string”:”test2″}]’ | curl -d @- localhost:3000/addDoc

The command pipes the string output from the echo command into the curl command. With a get request you can use visible parameters, like localhost/addDoc?param1=test. With a post request the parameters are hidden. Here I use curl to add the parameter ‘docs’ with a value of a JSON object to send the request.

The second route is a get request to /ld (latest documents). This route has visible the visible parameters amount and skip. So localhost:3000/ld?amount=3&skip=2 will skip the two latest documents added but get the 3 next and return the contents as a JSON object.

One particular issue i bumped into which took some troubleshooting was the fact that in the new versions of express (or node?) it is necessary to import and use a body-parser to url encode particularly the passwords sent to the MongoDB server. Otherwise special characters in the password will get escaped resulting in an authentication error.

I’m pleased to get the app working. Now that I know how to setup basic interaction with the mongoDB server, I have decided to move on to start learning Angular. This will give me a better overview of what features i need to implement on the Node.js Express app.

 

MongoDB University course completed and more posts to come..

So it’s been a while since the last post, it’s Summer! but i havn’t been completely idle. Since the last post I:

– completed the MongoDB University course, which will be the topic of this post.

– started working with Node and Express to experiment with making a RESTful server app for my blog application.

– completed the Angular tutorial: tour of heroes, to get started with Angular.

The next two posts will be about Node and Angular respectfully. This post will be about MongoDB and the course completed.

So here it is:

I completed the third part of the course, as well as the exam, while on vacation. The third part was interesting and a little challenging at times. While the final exam was so easy, I had to double check my results to check there wasn’t a trick question.

The third part was about query operators and projection operators.  Specifically:

  • Comparison operators: like $gt, $lt, $eq, $ne
  • Element operators: $type, $exists
  • Logical operators: $and, $or
  • Array operators: $all, $size, $elemMatch
  • Evaluation operator: $regex

Overall the course was a very good overview of how to use MongoDB, Compass, and Atlas. I feel confident in and look forward to working with MongoDB for my future applications.

MongoDB university and focusing on the basics.

So it’s been a week since my last update. Time went pretty fast, I’ve been busy with other things in life. I never finished that Nodes Express blog server app I mentioned last post. I made some progress with the skeleton from the MEAN/MERN tutorial. I attempted to copy over few things at a time and write just one of my REST commands. I never got to test it though, I had troubles navigating the Express part of the installation that required a html view, which i’m not really interested in migrating from the tutorial yet. In fact I would prefer to start without a html interface and just use curl commands against the server.

So to remedy this situation I have decided to focus even more on the basics and start looking into the Express basic tutorials. Hopefully that will enable me to navigate the Blog project and determine how to include what i want and need.

Today I continued with the MongoDB university course, week 2. It was a nice walk through of the Mongo shell client. With which you can query the mongodb databases.
I learned about the CRUD (Create, Read, Update, Delete) commands.
Mongodb has InsertOne, InsertMany, UpdateOne, UpdateMany, RemoveOne, RemoveMany functions that all use a filter to find one of many documents and operates on them. To operate it uses operators such as $set or $addtoarray. Besides the filter and operators you can also specify some additional parameters. Such is Upsert. Upsert = true in a Update command will create the document if there is none all ready that matches the filter.

The course still seems pretty simple, the lab tests this time required some console work, but were quick to accomplish. I’m looking forward to the last chapter of the course next week.

Get to work!

So.. It’s difficult to get started with the actual coding. It’s not unexpected. Today i had set time aside for working on the blog project, but it never came to much more than research and it little design speculation.

I started reading the 4th article in the tutorial I’m following about the Angular part of the MEAN stack.

It got into explaining the setup of Typescript, which I fear is not up to date. I looked at the Typescript website and they had many guides as to how to setup Typescript for many different environments, which was a bit overwhelming.

At first i need to focus on creating a RESTful server with Node and Express. It really seems doable.

I wrote down what requests i would like to have and what data i believe they should carry. I think security will be an issue, but i will just worry about it later.

The requests I’d like are:

Request x newest documents skipping y documents.

Request document by ID

Update/create document by ID

Delete document by ID

My goal is to have a basic version of the server running tonight.

First day of M001: MongoDB Basics

So today the free online course started. It was a series of videos, mainly showing the Compass tool (A GUI to the DB), while explaining the data structure. Basically on you have a cluster of databases, in each database there is a number of collections, each collection has a number of documents and each document has a field and each field has a value type, that could also be a document an array.

So an example for instance was:
database: videos
collection: movies
a given document in the collection:
_id: int32
cast: array
similarMovies: document

The course is split into four chapters, one for each week with the fourth chapter being the exam. I completed the entire chapter one, including lab assignments easily and within an hour. The lab assignments have to be submitted within 7 days but this week was definitely no challenge. Each of them consisted of a single multiple choice question that required you to make use of the Compass tool to find the answer in the databases. For instance it could be, how many movies was directed by “Jan Jansen” or similar.

I certainly did learn something, but I hope the course will also dive into using actual code, as this merely seems like a walk through of their product.

The next chapter is made available next Tuesday. Until then I suppose I will look more into the MERN and MEAN tutorial, and maybe start slowly to experiment with saving Blog data in a database via Node.

A short update

So last night I started reading the tutorial on The Mean and Mern stack and tried to follow along. Even though the article is only a year old, I had a lot of trouble getting their example to work because parts of it had already been outdated.

They use a Mongo Atlas database, which is a convenient way to run a database server for testing. However mongo driver they used in the example were outdated and it took me a while to figure out that was the problem. Updating it was effortless though.
I also had some problems renewing the Mockaroo link as they requested I did. Mockaroo is an online tool to create mock data for testing. I ended up just using their supplied link.

While walking through the code they used the Javascript ‘promise’ quite a lot. I struggled to understand the code that used the promise since it’s a new concept for me. In the end I looked it up and got smarter.

doSomething()
.then(result => doSomethingElse(result))
.then(newResult => doThirdThing(newResult))
.then(finalResult => {
console.log(`Got the final result: ${finalResult}`);
})
.catch(failureCallback);

I had troubles understanding where the result variable came from. It seems as it it defined and used as a variable without being set. However I see that it is like LINQ. ‘result’ is the return of the doSomething function and used as parameter to the doSomethingElse function.

Later today the Mongo University course should start, i’m looking forward to that.

Good News Every One!

I’ve signed up for a free online mongoDB basics course by MongoDB University!

It spans three weeks, with a 90 minute video released each week, with assignments, grades and a certification in the end. It starts already tomorrow :O

I’ve also found some good starting tutorials at mongoDB’s site.
A back to basics 4 part course, that seems to cover a lot of information about database basic terminology.
As well as a 6 part course about the MEAN and the MERN stack.
MEAN being:
MongoDB-Express-Angular-Node.JS
MERN being:
MongoDB-Express-React-Node.JS

So this seems to be exactly what I would want. Of course I havn’t looked closely at the content yet. So there’s a lot of learning ahead, at the same time I don’t wish to get too far off course. The mission is still to build a blog from scratch.

A little digging around

The first mission in my quest to become a full stack developer is to build a blog from scratch. To get started I looked into Node.js. After digging around a bit and finding some less useful tutorials I rediscovered W3schools. A very useful and free resource for learning web technologies.

Reading through their Node.JS documentation I quickly realised, while learning Node.js seems fairly straight forward, there seems to be no guide as to how to architect an application or database. So I started by reading a lot of material about backend development. In this post I will share some of these sources and talk about how I will proceed in my quest.

In particular I found this site very useful:
https://www.upwork.com/hiring/development/a-beginners-guide-to-back-end-development/

They very clearly explain and show what’s going on when you send a http request from your client.

They also explain the difference between SQL and NoSQL of which I was a tad confused. On W3Schools NodeJS tutorial there was also a tutorial of how to use and connect to MongoDB (a NoSQL database) and how to use and connect to MySQL (a relational database). So I’ve learned that a relational SQL (Structured Query Language) database stores data in tables. This allows for complex queries because you can filter the data based on the rows in the database. A NoSQL (Not only SQL) database stores data in a Key Value pair, like a dictionary. I realise this was the main type of database we used at my former company for our game. MongoDB is of the type that is document oriented. Which means that one key has a value that is basically a whole document of data. Like an xml or json document.
Here is a nice image showing the difference:

So going forward I think it’s important I explore the difference between relational databases and non-relational databases. In particular MySQL and MongoDB since these are referred to by the W3School tutorials anyway.

I’ve tried to find an explicit tutorial on how to create a blog using React, NodeJS and MongoDB but I didn’t have the patience to wade through the sea of ‘pay to play’ tutorials. However, here’s what I’ve found:

https://resources.mongodb.com/getting-started-with-mongodb

MongoDBs own resources to getting started. They seem to have many useful tutorials including;

  • Your First MongoDB Application
  • Getting Started with MongoDB, Node.js and Restify
  • Using ReactJS, ES6 & JSX to Build a UI

    It seems I have found the right place to start. I also found that W3Schools have a whole series of how-tos when it comes to frontend design. This will be a good place to start when I need to make the front end of the blog.

I’m very optimistic about this process now. I’ve managed to get Node.js to run on my computer and tried examples from W3schools. I’ve read insightful articles about the anatomy of a web application and the backend.

My next step will be to explore MongoDBs tutorials.