Categories
Angular Javascript MEAN stack Typescript

How to use and customize Angular Material snackbars

I will write this post because, despite it is a wonderful component,  customizing Angular Material snackbars is easy but sometimes can be a little tricky.

What is a snackbar?

https://material.angular.io/components/snack-bar/overview

As they say in the documentation, snackbar is a service for displaying snack-bar notifications.

To use it you must install angular material

https://www.npmjs.com/package/@angular/material

We hope Angular Team don´t deprecate it like they have done with the popular flex-layout library. which maybe will suppose a big problem for many projects where devs will have to spend weeks or months refactoring to CSS. I hope this is not the way Angular will take in the future.

https://betterprogramming.pub/farewell-flex-layouts-is-angular-starting-to-become-a-worry-4eea953b717b

Well, once we shared that disappointing news for the Angular community, we will focus on this helpful component, which is very useful to show messages to the user on the screen, in a very easy way.

We will take as example the Superheros app I am currently creating (yep, not the most original thing, I know 😛 ).

With snackbars I can notify the user when one hero has been successfully created; or when it has been deleted; or when an error occurs.

As you see, we have created a new hero with no problems and the user has been properly informed.

And, what if an error happens? We could also inform if, for example we try to create a new hero with no name. That is not allowed so in this case snackbar will throw an error and it will be red

Of course we could disable the “save” button until required conditions to create one hero are fulfilled, but this way I can  show you the uses of snackbar for this purpose.

Well, we will show the code. If we go again to the documentation, all snackbars are white by default:

But if we go to the element´s API, we will find a property called “panelClass” which allows us to use one string or array of strings, corresponding to the names of the CSS classes that will help us to customize our snackbar.

https://material.angular.io/components/snack-bar/api

LET´S CODE

So, ok, we will start writing our snackbar.

First of all, you will have to import the Module, like explained in the documentation:

That Module will contain everything you need to use your snackbars.

Where do you have to import it? Well, it is a Module, so we could import it on the main app.module.ts of the application, but, as when we use material components we end up having a lot of modules imported, I recommend creating another module only to declare the material components we will use.

For example: create a folder and inside a file with the name material-module.ts

Notice that here we have only used the exports[] array, while many times we also import the modules with the imports[] array, for example, in the app-module.ts

We can see why here:

https://stackoverflow.com/questions/39062930/what-is-the-difference-between-declarations-providers-and-import-in-ngmodule

  • imports makes the exported declarations of other modules available in the current module
  • exports makes the components, directives, and pipes available in modules that add this module to imports. exports can also be used to re-export modules such as CommonModule and FormsModule, which is often done in shared modules.

So, what we have in our material-module, is a module that will export the Angular Material modules, so they can be used on another module with the imports[] array. We need nothing more here.

Then, those exported Material Modules will be used, in my case, in another module called heroes-module.ts, just simply by importing the MaterialModule. That way, we will have with one sentence all the exported modules available for our heroes-module.ts. dependent components. Those dependent components are inside the “declarations” array.

IMPORTANT: Depending on the Code editor you use, maybe you will have to import manually the components or modules you specify in the @NgModule, inside declarations[], imports[]… arrays. Visual Studio Code makes for you.

Well, now we are able to use our snackbar in our components. In my case for this example is the add-component.ts which I use to add new heros

Why can we use Snackbar inside this component now? Because remember: inside the heroes-module.ts, we declared the AddComponent, as well as we have imported also in heroes-module.ts our MaterialModule.

So, AppComponent “depends” on heroes-module.ts,  which can “share” with its dependent components all the modules imported on heroes-module-ts, like for example our MaterialModule

If that sounded a bit confusing, maybe this scheme helps you:

Check the gists and I will stress the aforementioned  stack overflow link where they talk about import, exports, declarations…

https://stackoverflow.com/questions/39062930/what-is-the-difference-between-declarations-providers-and-import-in-ngmodule

So, now, in the component where we need to show our snackbar, we will have to inject it in the constructor. Why? Because, as we have read at the beginning, from the doc:

MatSnackBar is a service for displaying snack-bar notifications.

And what means that it is a service? That we have to inject it (more about dependency injection here). So, in our add-component.ts:

Now in this same component,  I will create a method to show our snack bar when needed, with the customizations we wish.

EDIT: Sorry for the mistyping, in the code I wrote “succesful” instead of “successful”

As we can see, our showSnackBar() method  has 2 parameters:

  • messageToShow. As it says, the message will be shown
  • snackBarClass. In my case there will be just one string. Please notice, we have passed a default value to this parameter. It is a string with the name of the CSS class that will be used most of the times. Declaring a default value you can in this case simply call the method passing the first parameter and will show “successful” styles by default. We will see later.

Our inject service is called “snackbar”, and we will call its open() method.

Here you can find info about the method and the parameters it accepts, but basically is responsible for showing –opening- our snackbar.

https://material.angular.io/components/snack-bar/api

  • Our first parameter is the messageToShow, that will be taken from the first parameter of showSnackBar(). As you can see this method acts like a wrapper to make it easier later to call and open the snackbar.
  • Second parameter “Close!” is just the text that will be shown, you can push on it, and the snackbar disappears before the set duration ends
  • As third parameter we have an object where will use two properties:
    • Duration. Simply the ms (milliseconds) you want the snackbar to stay on screen. 1000ms=1 second.
    • panelClass. This is where we will pass our css customizations. In this case we will pass the snackBarClass which, if we remember, has the value “successful”. So in anyway, now it would be like writing:
panelClass:”successful”

So now, we only have to call our showSnackBar()  where we need, with the appropriate message to be shown, For example, when we correctly add a new Hero.

And we will have:

Have you noticed how, as we call the method, we only passed the value to the message parameter? That saves us time and work, since we passed a default value for the second parameter and then we don´t need to specify a value if it is not different from the default value (we will see that later).

But ey! Where are the css classes we need? Where is our “successful” class?

Maybe you would place it on the add-component.css , but if you do that, it won’t work, as explained here:

https://stackoverflow.com/questions/47901127/angular-5-material-snackbar-panelclass-config

Accepted answer tells us WE MUST DO IT IN OUR GLOBAL STYLES.CSS FILE

So we will go there and we will write 2 classes: our old friend “successful” and another to show different styles if there is an error

Now, if we want to show a different style when an error occurs, we will have to call the method this way:

Can you see this time we are passing also the value to the second parameter? This way, we overwrite the default value passed to the panelClass from “successful” to “fail”).

As we have already seen, this will allow us to show a proper error message with a red background:

And that’s it! Is not very difficult but having to declare the snackbar classes on the global styles.css can give you some headaches and I want to save them for you 🙂

Also we have reviewed some cool Angular concepts which maybe are useful to you.

Of course as I always say, please feel free to contact me if you find some kind of failure, or if you want to hire me as technical writer for your publication.

 

Cover image belongs to Lawrence Monk found in Pixabay

Categories
Javascript Node npm

No more free Heroku? How to move your Node backend to Render.com

node js logoRecently I was reviewing the code for my spotiapp project, based on Spotify API. It is not fully 100% responsive but it is one of the apps I feel more proud of, when I watched it live for the first time I felt so GREAT. Sure can be better but as I say I am proud of it.

My backend was hosted in Heroku. I was pretty happy with the service Heroku was providing me, but when I wanted to make some small changes to the backend code, I found this message:

 

 

That means, Heroku offers no more free plans. Of course I can’t blame them: a company is supposed to make money, so I am sure they have good reasons to do that.

But I am workless now. This “spotiapp” is only made with educational purposes, and to include it in my portfolio and show potential employers or clients what I can do; so as you can guess, it is not only enough with a free plan, but I can´t start paying a fee to host every app I build.

Let me state that this is not a “look for some free options then you can avoid paying” tutorial. I think good services must be paid. We are developers and all of us like to be paid, isn´t it? I myself pay for a hosting to include all my projects and my portfolio . It is a reliable provider with an excellent service, where I can host all my apps; but unfortunately, I can´t build Node-based servers there.

In the future, when I build commercial apps which can potentially help me buy money, of course I will upgrade my account, but now, for tests, small apps and learning purposes, as I said, I can´t be paying for each app with a node-based back end I write.

To be honest I only had this app hosted with Heroku. Most of my backends are done in PHP so there is no problem, my actual paid host does the job; but I am a frontend Angular developer and to become a more full-stack dev, I want to start building more node-express backends.

 

HEROKU DYNOS MODEL

 

With their model (or so I understood), you have to pay for each “dyno” (containers used by your app). Your app could need one or more dynos depending on size and demands. If you have to pay, for example $7 dyno per month for the Hobby plan, and you have 20 apps running their backend on heroku, maybe now you probably simply can´t afford it, like it is my case.

More info about “dynos” here:

https://www.heroku.com/dynos

 

A free option with Render.com

 

As you can guess, there are many alternatives out there. I will refer you to this excellent article where they will explain better than me. I will focus on teaching you how to move a basic backend from heroku to Render.com, the provider I selected, which still allows a free plan, and is very easy to use and well implemented with GitHub.

Will Render.com charge me?

We can see how Free plan works:

https://render.com/docs/free#free-web-services

When you exceed your free usage limits (i.e., usage hours and/or bandwidth), free services in your account are automatically suspended and can no longer serve traffic until they are upgraded to a paid plan or when free usage is reset at the end of the calendar month, whichever is sooner.

Free usage is reset on the 1st of every month, and all free services suspended for usage limits are automatically resumed.

 

So I guess we are safe with it. Also no credit or debit card is required to register, as you can see here, so it definitely gives me some tranquility.

 

 

HOW TO MOVE OUR BACKEND FROM HEROKU TO RENDER.COM

 

So, let´s go with it.

Before you do nothing, when you register in Render.com, I recommend you read the docs , because it will help you a lot and quickly.

If you want to make a small tutorial about how to deploy a node/express backend, on the doc´s Quickstart section, we will choose this:

 

 

This will prompt us to a super easy tutorial where you can fork an existing repo, with all the needed steps to deploy:

 

 

This doesn´t mean you have to use the exact same commands for all your projects. For example, in my backend you can see I have package.json files, that means our dependencies will be installed with npm install and not with yarn . Both are two different package managers and you can read more about them here.

https://phoenixnap.com/kb/yarn-vs-npm

So ok, I assume you have a GitHub or GitLab profile, and you have registered on Render.com.

Whether you make the tutorials or not, the first thing after registering is to connect your GitHub account with your profile. There you will be able to choose if you give access to all your repos or only selected ones.

So, we go to the setting and connect to GitHub

 

 

Once you are connected, it will ask you for permissions or which repos you want to give access to. However, you can control it form your own GitHub Profile:

Go to your GitHub settings and click integrations/applications

 

 

There you can configure your render app:

 

 

This option will allow us to grant permissions for one or more repos. Of course before we do it, in this case we have to push our backend code to GitHub if we haven´t already there.

This is my Heroku backend. It is very simple:

 

  • A .js file with all the logic needed to make connections to the spotify API and such.
  • json and package-lock.json files, to help you install the required dependencies your backend needs.
  • Procfile. This is one Heroku exclusive file which executes commands by the app on startup. This won´t be needed on Render.com, of course.

In my case,  I will delete the Procfile since, as I said, it is no longer needed as it is one Heroku file.

 

 

Ok, let´s go back to configure our Render installed app in GitHub

 

 

Now you can manage Render´s access to your repos. In my case I only gave permission to the repo of this backend and the one for the tutorial I did before:

 

 

Now we save, and go back to Render´s page, to our dashboard.

We can choose there “New”, and then “Web Service” option, or just click directly on “Web Services”. Both will do the same.

 

 

Now it will ask you to connect one of the repositories you granted permissions before, on GitHub. We will choose our node back end server for render

 

 

Now it will ask us to provide some data

 

  • The name is not mandatory to be the same as your GitHub repo’s, I will simply write “spotiapp-backend”
  • Root Directory will be left as it is
  • Environment will be Node

Next options:

 

 

Leave region and branch as they are. The important thing now is the build command. It usually appears “yarn” as default. But, do you remember we have a package.json? That means the dependencies must be installed with “npm install”.

Next steps are also important. The start command will be the same you would use on your terminal to run the app. In my case, the main file is called “index2.js”, and to run this node server we will use the “node” command.

Also check the free plan type.

 

 

As they remind you, remember free plans, same as happenned in Heroku, shut down your apps after a time of inactivity, and it takes a little longer than usual when they have to reactivate again.

Now push “Create Web Service” at the bottom of the page:

 

 

This will lead you to another screen with a terminal where your app will be deployed. The URL of the app should now be copied on your frontend code or whereever you pointed to heroku old address before.

 

 

Wait until it finishes and, remember, once you have changed the old heroku address from your old web servers everywhere you need in your code, you now have a free, working Node/Express backend ready to use 🙂

THE DRAWBACKS

I have still not tested enough, but the only cons I found now is that you must pay if you want to use CRON JOBS.

  • CRON JOBS are very useful if you have a test app where users can post or edit data, and you want to schedule this data to be reset every certain time, so you can be sure that only the test/ default data you provided, will be kept at last. It is not included with Free plan, but as I said, companies are there to earn money so probably I will pay for this if I need it.
  • Also the web is a bit slow sometimes and throws some errors, but nothing important by now.

So, I hope this article helped you to deploy your node services easily on a free alternative to Heroku. However, remember, if you start making money with your apps, please value the other´s efforts and upgrade your plan.

 

Node image by CopyrightFreePictures found in Pixabay

Categories
Misc Silly Wise Tips What have I learned?

How to know when one Udemy course was created

Many times, when you purchase a course on that platform, (specially software related ones), you could find they are quite old and outdated to the point you could spend more time fixing deprecated methods, fixing errors… than actually doing the course. Must say that fixing errors is sometimes a good way to learn, but usually we expect that the authors update them more often.

Unfortunately that is not always the case, and worse, those authors sometimes update the title of the course to reflect the current year or one framework’s / programming language´s latest version in an attempt to hide the outdated concepts and get more sales.

Now it seems it is not possible to see when a course was created, just the last update.

last-update-udemy-caption

But there is a way to find when it was actually created using the Udemy API. We can use our preferred api platform to perform the request. I use Postman.

We must make a request to the following endpoint:

https://www.udemy.com/api-2.0/courses/COURSE_ID/?fields[course]=title,url,created

We need just to change COURSE_ID with the actual id of the course. How can we find it?

Go to the course´s main page, right click and select View page source (you can open it with CTRL + U ). Once you are there, use CTRL + F and look for the attribute called data-clp-course-id, where you will find the course id.

Once you change COURSE_ID with the id you are have been provided, perform the request and if everything goes fine you will get a response with a field called “created”, where you can see the course creation date.

created-field-udemy-api-response

Hope it helps.