Instagram launches video chat

Facebook today announced that Instagram, its popular photo-sharing platform, is getting support for video chats, among a couple of other new features. As Facebook co-founder and CEO Mark Zuckerberg noted in his F8 keynote today, quite a few Instagram users already use the platform’s live video feature to chat with friends. “People use live video to just hang out,” he said. “It’s amazing how many of these tools are about bringing us together.” We haven’t seen the new video chat in action, but chances are it’s a pretty straightforward feature that will expand on the existing messaging tools in Instagram. In addition to these video chats, Instagram is also getting an improved Explore tab that, according to Zuckerberg, is “more focused on the things you are interested in.” <pre></code> Instagram is also getting a new filter to protect users from bullying comments. “This new filter hides comments containing attacks on a person’s appearance or character, as well as threats to a person’s well-being or health,” the Instagram team writes today. In addition to the automatic filtering, Instagram will now also get alerts when there are repeated issues with an account. <pre></code> But that’s not all; Instagram is also getting support for Facebook’s AR features with AR features from third parties. The company made the announcement at its F8 developer conference in San Jose today, where the company also announced a somewhat related new feature: group video chats in WhatsApp. These new features will roll out over the course of the next few weeks.

Read more

The Difference Between Responsive and Adaptive Design

Responsive web design has become a household term since it was coined by Ethan Marcotte on A List Apart in 2010; so much that we may take our understanding of it for granted. The concept of a responsive website is one of the greatest CSS "tricks" in the books and important enough to step back from in order to both remind ourselves what makes a "responsive" website and how it's different from an "adaptive" one. So, with that, let's look at the difference. #The Short Explanation Responsive sites and adaptive sites are the same in that they both change appearance based on the browser environment they are being viewed on (the most common thing: the browser's width). Responsive websites respond to the size of the browser at any given point. No matter what the browser width may be, the site adjusts its layout (and perhaps functionality) in a way that is optimized to the screen. Is the browser 300px wide or 30000px wide? It doesn't matter because the layout will respond accordingly. Well, at least if it's done correctly! Adaptive websites adapt to the width of the browser at a specific points. In other words, the website is only concerned about the browser being a specific width, at which point it adapts the layout. Another way to think about it is the difference between smooth and snap design. Responsive design is smooth because the layout fluidly adjusts regardless of what device it is viewed on. Adaptive design, on the other hand, snaps into place because the page is serving something different because of the browser or device it is viewed on. This animation illustrates the difference in behavior: Responsive on top, Adaptive on bottom Notice how the responsive example flows with the environment whereas the adaptive snaps into place at a defined environment. #The Longer Explanation The difference between responsive and adaptive sites goes a little deeper than the simple examples above. You might even think of it as a difference in philosophy. Let's consider the crux of Ethan's original definition of responsive web design: Fluid grids, flexible images, and media queries are the three technical ingredients for responsive web design, but it also requires a different way of thinking. Rather than quarantining our content into disparate, device-specific experiences, we can use media queries to progressively enhance our work within different viewing contexts. Notice the operative words fluid and flexible. Responsive design is a means of becoming device agnostic in the sense that it seeks to create an optimized experience for any screen. This thinking challenges us to create sites that shift context according to how a site is being consumed on any given occasion. That means our containers should be fluid (as in using percentages as unit measures), the assets we serve should be flexible (as in serving the right assets to right devices at the right time) and our media queries defined where content breaks (as opposed to the width of a specific screen size, say iPhone). Compare that with an adaptive way of thinking, which is neither fluid nor flexible, but looks for specific points at which to adapt. While it might be difficult to adapt a website on all the various devices out there, there's a roundup of device-specific media queries you can refer to. Update: There has been a lot of awesome conversation in the comments about the difference between responsive and adaptive design. The important takeaway is that the difference comes down to more than media queries and pixel units. The animated GIF example earlier in the post is one way to illustrate the difference as those terms are recognized here, but this post also provides a nice series of illustrations to drive the point further. #Is Responsive Better Than Adaptive? I'm not even going to go there. I believe it's a difference in philosophy, just as responsive web design is from mobile-first responsive web design. You choose the best tool for the project at hand. Are you forced to choose one over the other? The choice might be easier if you know that you have specific devices your site must support. You might decide that iPhone 6 is the only device that matters and adapting to it wold be a lot easier and more efficient than accounting for other devices. On the flip side, a responsive design is a good strategy for future-proofing a site against the possibility of any (perhaps even unreleased) device on the market. #The Bottom Line Both responsive and adaptive designs are the same in that they are methods for dealing with the reality that websites are often viewed on different devices in different contexts. They just happen to go about it in their own ways. <blockquote class="quote-card blue-card"> Remember: the web is responsive by nature. It doesn't need to respond or adapt to any devices until we start designing it. <blockquote> If you're looking to dive into responsive design, the best thing to do is practice. There is no shortage of resources out there to help you get started, so have at it! Here are a few to get you started: This is Responsive: A collection of examples, patterns and resources curated by Brad Frost. ResponsiveDesign.is: Another treasure trove of resources, in addition to articles and a podcast! Responsive Web Design Podcast: Speaking of podcasts, here's one co-hosted by Ethan Marcotte and Karen McGrane. Responsive Web Design, by Ethan Marcotte: Ethan literally wrote the book on it and did so with the utmost clarity.

Read more

Facebook announces dating feature for meeting non-friends

Facebook is invading Tinder’s space with a new set of dating features. It will let people opt in to creating a dating profile on Facebook. It will only be visible to non-friends who also opted into dating. Facebook will match you by a slew of preferences. And because it has more data on you than any other app, it could deliver more relevant matches. The feature will start testing later this year.Facebook explains that “potential matches will be recommended based on dating preferences, things in common, and mutual friends. They’ll have the option to discover others with similar interests through their Groups or Events.” TechCrunch suggested that Facebook build a feature like this in February.Here’s how Facebook dating will work:Tons of marriages start on Facebook already, so there’s a big opportunity for the company to build long-term relationship-focused matching — opposed to apps like Tinder that focus on quick hookups. Investors clearly think Tinder is in danger, considering shares of its parent company Match Group fell 17 percent after Facebook announced its entry into dating.Still, the question is whether Facebook has built enough barricades between its social network and new dating feature. Users might find it creepy to do it all in one app. And if they get burned by a bad experience either in the dating chat or offline, they could blame Facebook. Still, as Facebook Chief Product Officer Chris Cox explained, dating was always a natural fit for Facebook thanks to its ubiquity, data and trusted platform for identity.At the very least, you’ll be a lot less likely to get catfished on FaceDate.We explored how this could work in a feature piece earlier this year:Facebook should actually be Tinder too

Read more

What are Higher-Order Components in React?

By Kingsley Silas On April 19, 2018 react, react props If you have been in the React ecosystem for a while, there is a possibility that you have heard about Higher Order Components. Let’s look at a simple implementation while also trying to explain the core idea. From here you should get a good idea of how they work and even put them to use.As you build React applications, you will run into situations where you want to share the same functionality across multiple components. For example: you need to manage the state of currently logged in users in your application. Instead of managing that state across all of the components that need that state, you could create a higher-order component to separate the logged in user state into a container component, then pass that state to the components that will make use of it.The components that receive state from the higher-order component will function as presentational components. State gets passed to them and they conditionally render UI based on it. They do not bother with the management of state.Let's see another example. Say you have three JSON files in your application. These files contain different data that will be loaded in your application in three different components. You want to give your users the ability to search the data loaded from these files. You could implement a search feature in all three of the components. This duplication may not be an issue at first, but as your application grows and more components need this functionality, the constant duplication will be cumbersome and prone to problems.A better way forward is to create a higher-order component to handle the search functionality. With it, you can wrap the other components individually in your higher-order component.The React docs say that higher-order components take a component and return a component. The use of higher-order components comes in handy when you are architecturally ready for separating container components from presentation components. The presentation component is often a stateless functional component that takes props and renders UI. A stateless functional components are plain JavaScript functions that do not have states. Here’s an example:The container component does the job of managing of state. The container, in this case, is the higher-order component.In the search example we talked about earlier, the search component would be the container component that manages the search state and wraps the presentation components that need the search functionality. The presentation components otherwise have no idea of state or how it is being managed.Let's start with a basic example. Here’s a higher-order component that transforms and returns usernames in uppercase:This higher-order component receives a WrappedComponent as an argument. Then it returns new component with props passed to it creating a React element. We call .toUpperCase() on the props.children, to transform the passed props.children to uppercase.To make use of this higher-order component, we need to create a component that receives props and renders the children.Next, we wrap Username with the higher-order component. Let's store that in a variable:In our App component, we can now make use of it like this:The UpperCaseUsername component is merely a rendering of the Username UI that, in turn, pulls in state from the WrappedComponent acting as the higher-order component.Imagine we want to create a list of locations with a search form that filters them. The JSON will be in flat files and loaded as separate components. Let’s start by loading the data.Our first component will load locations for our users. We will make use of .map() to loop through the data contained in that JSON file.This component will render the data in a LocationCard component. I moved that to a different component to keep things clear. This component is a functional component that handles the presentation of our data. The data (location) from the file is received via props, and each location will be passed down to the LocationCard component.Now we need a second component that, eventually, also will need search functionality. It will be very similar to the first component we just built, but it will have a different name and load data from a different place. We want our users to be able to search for items using an input field. The list of items displayed on the app should be determined by the state of the search. This functionality will be shared across the two components we are working on. Thanks to the idea of higher order components, we can create a search container component and wrap it around other components.Let's call the component withSearch. This component will render the input field for our search and also manage our searchTerm state. The searchTerm will be passed as props to the wrapped component, which will be used to filter the pulled data:The searchTerm is given a state of an empty string. The value entered by the user in the search box is obtained and used to set the new state for searchTerm. Next, we pass searchTerm to the WrappedComponent. We will make use of this when filtering the data.To make use of the higher-order component, we need to make some changes to our presentational component.The first thing we did above is to import the higher-order component. Then we add a filter method to filter the data based on what the user enters in the search input. Last, we need to wrap it with the withSearch component.See the Pen hoc Pen by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.Higher-Order Components do not have to be scary. After understanding the basics, you can put the concept to use by abstracting away functionalities that can be shared among different components. Show Comments Great writeup, @KingsleyIt’s worth mentioning that Higher Order Components can carry some extra baggage, passing down data that’s not necessarily used by its wrapped component. Take a look at the discussions popping up around Render Props as a replacement to Higher Order Components.I can do anything you're doing with your HOC using a regular component with a render prop. Come fight me.— MICHAEL JACKSON (@mjackson) July 14, 2017 View story at Medium.comYou may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic. Email Address CSS-Tricks* is created, written by, and maintained by Chris Coyier and a team of swell people. It is built on WordPress, hosted by Media Temple, and the assets are served by MaxCDN. It is made possible through sponsorships from products and services we like.*May or may not contain any actual "CSS" or "Tricks".

Read more

Build a To-Do App with Vue.js 2

Vue is a simple and minimal progressive JavaScript framework that can be used to build powerful web applications incrementally.Vue is a lightweight alternative to other JavaScript frameworks like AngularJS. With an intermediate understanding of HTML, CSS and JS, you should be ready to get up and running with Vue.In this article, we will be building a To-Do application with Vue while highlighting the bundle of awesomeness that it has to offer.Let's get started!We'll need the Vue CLI to get started. The CLI provides a means of rapidly scaffolding Single Page Applications and in no time you will have an app running with hot-reload, lint-on-save, and production-ready builds. Vue CLI offers a zero-configuration development tool for jumpstarting your Vue apps and component. A lot of the decisons you have to make regarding how your app scales in future are taken care of. The Vue CLI comes with an array of templates that provide a self-sufficient, out-of-the-box ready to use package. The currently available templates are: Simply put, the Vue CLI is your is the fastest way to get your apps up and running.In this tutorial, we will be focusing on the use of single file components instead of instances. We'll also touch on how to use parent and child components and data exchange between them. Vue's learning curve is especially gentle when you use single file components. Additionally, they allow you to place everything regarding a component in one place. When you begin working on large applications, the ability to write reusable components will be a life saver.Next, we'll set up our Vue app with the CLI.You will be prompted to enter a project name, description, author and Vue build. We will not install Vue-router for our app. You will also be required to enable linting and testing options or the app. You can follow my example below. Once we have initialized our app, we will need to install the required dependencies. To serve the app, runThis will immediately open your browser and direct you to http://localhost:8080 . The page will look as follows.To style our application we will use Semantic. Semantic is a development framework that helps create beautiful, responsive layouts using human-friendly HTML. We will also use Sweetalert to prompt users to confirm actions. Sweetalert is a library that provides beautiful alternatives to the default JavaScript alert. Add the minified JavaScript and CSS scripts and links to your index.html file found at the root of your folder structure.Every Vue app, needs to have a top level component that serves as the framework for the entire application. Fo our application, we will have a main component and nested within shall be a TodoList Component. Within this there will be todo sub-components.Let's dive into building our application. First, we'll start with the main top level component. The Vue CLI already generates a main component that can be found in src/App.vue. We will build out the other necessary components.The Vue CLI creates a component Hello during set up that can be found in src/components/Hello.vue. We will create our own component called TodoList.vue and won't be needing this anymore.Inside of the new TodoList.vue file, write the following.A component file consists three parts; template, component class and styles sections. The template area is the visual part of a component. Behaviour, events and data storage for the template are handled by the class. The style section serves to further improve the appearance of the template.To utilize the component we just created, we need to import it in our main component. Inside of src/App.vue make the following changes just above the script section and below the template closing tag.We will also need to reference the TodoList component in the components property and delete the previous reference to Hello Component. After the changes, our script should look like this.To render the component, we invoke it like an HTML element. Component words are separated with dashes like below instead of camel case.When we have saved our changes our rudimentary app should look like this. We will need to supply data to the main component that will be used to display the list of todos. Our todos will have three properties; The title, project and done(to indicate if the todo is complete or not). Components avail data to their respective templates using a data function. This function returns an object with the properties intended for the template. Let's add some data to our component.We will need to pass data from the main component to the TodoList component. For this, we will use the v-bind directive. The directive takes an argument which is indicated by a colon after the directive name. Our argument will be todos which tells the v-bind directive to bind the element’s todos attribute to the value of the expression todos.The todos will now be available in the TodoList component as todos. We will have to modify our TodoList component to access this data. The TodoList component has to declare the properties it will accept when using it. We do this by adding a property to the component class.Inside our TodoList template lets loop over the list of Todos and also show the the number of completed and uncompleted tasks. To render a list of items, we use the v-for directive. The syntax for doing this is represented as v-for="item in items" where items is the array with our data and item is a representation of the array element being iterated on. Let's extract the todo template into it's own component for cleaner code. Create a new component file Todo.vue in src/components and transfer the todo template. Our file should now look like this:In the TodoList component refactor the code to render the Todo component. We will also need to change the way our todos are passed to the Todo component. We can use the v-for attribute on any components we create just like we would in any other element. The syntax will be like this: <my-component v-for="item in items" :key="item.id"></my-component>. Note that from 2.2.0 and above, a key is required when using v-for with components. An important thing to note is that this does not automatically pass the data to the component since components have their own isolated scopes. To pass the data, we have to use props.Our refactored TodoLost component template:Let's add a property to the Todo component class called isEditing. This will be used to dertermine whether the Todo is in edit mode or not. We will have an event handler on the Edit span in the template. This will trigger the showForm method when it gets clicked. This will set the isEditing property to true. Before we take a look at that, we will add a form and set conditionals to show the todo or the edit form depending on whether isEditing property is true or false. Our template should now look like this.In addition to the showForm method we will need to add a hideForm method to close the form when the cancel button is clicked. Let's see what our script now looks like.Since we have bound the form values to the todo values, editing the values will immediately edit the todo. Once done, we'll press the close button to see the updated todo. Let's begin by adding an icon to delete a Todo just below the edit icon. Next, we'll add a method to the component class to handle the icon click. This method will emit an event delete-todo to the parent TodoList Component and pass the current Todo to delete. We will add an event listener to delete icon.The parent component(TodoList) will need an event handler to handle the delete. Let's define it.The deleteTodo method will be passed to the Todo component as follows.Once we click on the delete icon, an event will be emitted and propagated to the parent component which will then delete it.To create a new todo, we'll start by creating a new component CreateTodo in src/components. This will display a button with a plus sign that will turn into a form when clicked. It should look something like this.After creating the new component, we import it and add it to the components property in the component class.We'll also add a method for creating new Todos.The CreateTodo component will be invoked in the App.vue template as follows:Finally, we'll add a method completeTodo to the Todo Component that emits an event complete-todo to the parent component when the pending button is clicked and sets the done status of the todo to true.An event handler will be added to the TodoList component process the event.To pass the TodoList method to the Todo component we will add it to the Todo component invokation.We have learned how to initialize a Vue app using the Vue CLI. In addition, we learned about component structure, adding data to components, event listeners and event handlers. We saw how to create a todo, edit it and delete it. There is a lot more to learn. We used static data in our main component. The next step it to retrieve the data from a server and update it accordingly. We are now prepared to create interactive Vue application. Try something else on your own and see how it goes. Cheers!📺 Latest Courses📑 Latest PostsI'm a Full Stack Developer at Andela, (Mostly JavaScript & Python). currently interested in Go.I'm a Full Stack Developer at Andela, (Mostly JavaScript & Python). currently interested in Go.Top shelf learning. Informative tutorials explaining the code and the choices behind it all.or do the email thingCreate an account now to get access to all premium content.

Read more

Vue.js 2 Quickstart Tutorial 2017

This post has been published first on CodingTheSmartWay.com.Support Us With One Cup Of Coffee :)Vue is a progressive JavaScript framework that focuses on building user interfaces. As it only works in the “view layer” it makes no assumption of middleware and backend and therefore can be integrated easily into other projects and libraries. Vue.js offers a lot of functionality for the view layer and can be used for building powerful single-page webapps. In the following you can find a list of features:The Vue.js 2 core library is very small in size (only 17 kB). This ensures that the overhead which is added to your project by using Vue.js is minimal and your website is loading fast.   The Vue.js website is available at: https://vuejs.org/There are different ways to include Vue.js in your web project:In the following we’re going to the Vue-cli to setup a new project and install the Vue.js 2 library.First, we need to install Vue-cli. The commend line interface is available as an NPM package. Make sure that Node.js and the npm command is available on your system and use the following command to install the Vue CLI globally on your local system:  $ npm install -g vue-cli  Having installed the client successfully the vue command becomes available. Now we're able to initiate a project by using this command in the following way:  $ vue init webpack vueapp01  We're telling vue to initiate a new project and use the webpack template. We also give the project the name vueapp01. Executing the command brings up a few questions on the command line as you can see in the following screenshot:The project is created in the folder vueapp01. Change into that directory with the following command:  $ cd vueapp01  Start installing the dependencies by using npm again:  $ npm install  After having completed the installation of packages you can start the web server in development mode by using npm in the following way:  $ npm run dev  This will start the server on port 8080 and the application output is displayed in the browser automatically:Later, if you want to build for production you can use the following command instead. In this case a dist folder is created containing the files needed for productive deployment.   $ npm run buildLet’s take a look at the initial project structure which is available in folder vueapp01:In the project root folder you can find files and folders. Let’s examine the most important ones. The package.json files contains all the dependencies of your project. By using the command npm install before we have made sure that the dependencies listed in package.json are installed into the node_modules folder of the project.   The file index.html contains the following HTML code:This file is the starting point of your application. Note that within the body section a <div> element is available which has the id property set to string app. This element is used as a placeholder for the output which is generated by Vue.js.   Next take a look at file main.js in folder src. That's the place where the Vue application is initialized:On top of the file you can find two import statements:By using the new keyword a new instance of the main framework class Vue is created. The constructor takes an object as a parameter which contains three properties:The template only consists of one element: <App/>. Of course this is not a standard HTML element. This is the element which is assigned to App component. In order to be able to use <App/> in the template the App component is also listed in the object which is assigned to the components property.   So let's see what's inside the App component implementation in file App.vue:As in every Vue.js 2 single-file component the App implementation is split up into three parts:Let’s focus on the the first two sections template and script. The script section is making a default export of an object declaraing the component named app. Again, the components property is used to declare that another component (Hello) is required by App. This subcomponent is used in the template code of app and implemented in file hello.vue in folder components. In order to be able to use the Hello component in App it’s also needed to include the corresponding import statement on top of the script section.  The implementation of component Hello looks like the following:The component configuration object is exported as default. This time the component configuration object contains a data method. This method returns an object which represents the component’s model. Properties defined in the model object can be used in the component’s template by using the interpolation syntax. In the example from above the model object has only one property: msg. The string which is assigned to this property is included in the component’s template by using:  <h1>{{ msg }}</h1>  The interpolation syntax required double curly braces to include model data in the template.Let’s adapt the Hello component implementation to learn more about the usage of Vue.js standard directives.The v-for directive makes it possible to render an element multiple times based on source data. You can use this directive to iterate over an array and at the array data to the output. First add an array to the object which is returned by the data method:Then use the v-for directive to include a list in the output printing out the firstname and lastname value of each array element:The v-model directive creates a two-way binding on an input element or a component. Make sure to define a property in your data object which should be used as the binding target:Then use the directive to bind the value of an input element to that property:With that binding established we’re getting two effects:By using the v-text directive the text content of an element is set. We can use it as an alternative to the {{ … }} syntax if the complete text content should be set. E.g. we can use this directive to output the input_val value to the user:The complete code of the adapted Hello component implementation should now look like the following:The result can be seen in the following screenshot:This video tutorial contains the steps described in the text above:This post has been published first on CodingTheSmartWay.com.By clapping more or less, you can signal to us which stories really stand out.Fullstack JavaScript Developer, Author of Angular 2 Book leanpub.com/angular2-bookCodingTheSmartWay.com is a blog about latest web and mobile technologies.

Read more

GraphQL vs. REST - A GraphQL Tutorial

by Amaury Martiny - Full-stack Developer @ Toptal You might have heard about the new kid around the block: GraphQL. If not, GraphQL is, in a word, a new way to fetch APIs, an alternative to REST. It started as an internal project at Facebook, and since it was open sourced, it has gained a lot of traction.The aim of this article is to help you make an easy transition from REST to GraphQL, whether you’ve already made your mind for GraphQL or you’re just willing to give it a try. No prior knowledge of GraphQL is needed, but some familiarity with REST APIs is required to understand the article.The first part of the article will start by giving three reasons why I personally think GraphQL is superior to REST. The second part is a tutorial on how to add a GraphQL endpoint on your back-end.If you are still hesitating on whether or not GraphQL is suited for your needs, a quite extensive and objective overview of “REST vs. GraphQL” is given here. However, for my top three reasons to use GraphQL, read on.Say you have a user resource on the back-end with first name, last name, email, and 10 other fields. On the client, you generally only need a couple of those.Making a REST call on the /users endpoint gives you back all the fields of the user, and the client only uses the ones it needs. There is clearly some data transfer waste, which might be a consideration on mobile clients.GraphQL by default fetches the smallest data possible. If you only need first and last names of your users, you specify that in your query.The interface below is called GraphiQL, which is like an API explorer for GraphQL. I created a small project for the purpose of this article. The code is hosted on GitHub, and we’ll dive into it in the second part.On the left pane of the interface is the query. Here, we are fetching all the users—we would do GET /users with REST—and only getting their first and last names.QueryResultIf we wanted to get the emails as well, adding an “email” line below “lastname” would do the trick.Some REST back-ends do offer options like /users?fields=firstname,lastname to return partial resources. For what it’s worth, Google recommends it. However, it is not implemented by default, and it makes the request barely readable, especially when you toss in other query parameters:These query parameters are patches added to the REST API to imitate a query language. GraphQL is above all a query language, which makes requests concise and precise from the beginning.Let’s imagine we want to build a simple project management tool. We have three resources: users, projects, and tasks. We also define the following relationships between the resources:Here are some of the endpoints we expose to the world:The endpoints are simple, easily readable, and well-organized.Things get trickier when our requests get more complex. Let’s take the GET /users/:id/projects endpoint: Say I want to show only the projects’ titles on the home page, but projects+tasks on the dashboard, without making multiple REST calls. I would call:It’s common practice to add query parameters ?include=... to make this work, and is even recommended by the JSON API specification. Query parameters like ?include=tasks are still readable, but before long, we will end up with ?include=tasks,tasks.owner,tasks.comments,tasks.comments.author.In this case, would be it wiser to create a /projects endpoint to do this? Something like /projects?userId=:id&include=tasks, as we would have one level of relationship less to include? Or, actually, a /tasks?userId=:id endpoint might work too. This can be a difficult design choice, even more complicated if we have a many-to-many relationship.GraphQL uses the include approach everywhere. This makes the syntax to fetch relationships powerful and consistent.Here’s an example of fetching all projects and tasks from the user with id 1.QueryResultAs you can see, the query syntax is easily readable. If we wanted to go deeper and include tasks, comments, pictures, and authors, we wouldn’t think twice about how to organize our API. GraphQL makes it easy to fetch complex objects.When building a back-end, we always start by trying to make the API as widely usable by all clients as possible. Yet clients always want to call less and fetch more. With deep includes, partial resources, and filtering, requests made by web and mobile clients may differ a lot one from another.With REST, there are a couple of solutions. We can create a custom endpoint (i.e., an alias endpoint, e.g., /mobile_user), a custom representation (Content-Type: application/vnd.rest-app-example.com+v1+mobile+json), or even a client-specific API (like Netflix once did). All three of them require extra effort from the back-end development team.GraphQL gives more power to the client. If the client needs complex requests, it will build the corresponding queries itself. Each client can consume the same API differently.In most debates about “GraphQL vs. REST” today, people think that they must choose either one of the two. This is simply not true.Modern applications generally use several different services, which expose several APIs. We could actually think of GraphQL as a gateway or a wrapper to all these services. All clients would hit the GraphQL endpoint, and this endpoint would hit the database layer, an external service like ElasticSearch or Sendgrid, or other REST endpoints.A second way of using both is to have a separate /graphql endpoint on your REST API. This is especially useful if you already have numerous clients hitting your REST API, but you want to try GraphQL without compromising the existing infrastructure. And this is the solution we are exploring today.As said earlier, I will illustrate this tutorial with a small example project, available on GitHub. It is a simplified project management tool, with users, projects, and tasks.The technologies used for this project are Node.js and Express for the web server, SQLite as the relational database, and Sequelize as an ORM. The three models—user, project, and task—are defined in the models folder. The REST endpoints /api/users, /api/projects and /api/tasks are exposed to the world, and are defined in the rest folder.Do note that GraphQL can be installed on any type of back-end and database, using any programming language. The technologies used here are chosen for the sake of simplicity and readability.Our goal is to create a /graphql endpoint without removing the REST endpoints. The GraphQL endpoint will hit the database ORM directly to fetch data, so that it is totally independant from the REST logic.The data model is represented in GraphQL by types, which are strongly typed. There should be a 1-to-1 mapping between your models and GraphQL types. Our User type would be:Queries define what queries you can run on your GraphQL API. By convention, there should be a RootQuery, which contains all the existing queries. I also pointed out the REST equivalent of each query:If queries are GET requests, mutations can be seen as POST/PATCH/PUT/DELETE requests (although really they are synchronized versions of queries).By convention, we put all our mutations in a RootMutation:Note that we introduced new types here, called UserInput, ProjectInput, and TaskInput. This is a common practice with REST too, to create an input data model for creating and updating resources. Here, our UserInput type is our User type without the id and projects fields, and notice the keyword input instead of type:With types, queries and mutations, we define the GraphQL schema, which is what the GraphQL endpoint exposes to the world:This schema is strongly typed and is what allowed us to have those handy autocompletes in GraphiQL.Now that we have the public schema, it is time to tell GraphQL what to do when each of these queries/mutations is requested. Resolvers do the hard work; they can, for example:We are choosing the third option in our example app. Let’s have a look at our resolvers file:This means, if the user(id: ID!) query is requested on GraphQL, then we return User.findById(), which is a Sequelize ORM function, from the database.What about joining other models in the request? Well, we need to define more resolvers:So when we request the projects field in a User type in GraphQL, this join will be appended to the database query.And finally, resolvers for mutations:You can play around with this here. For the sake of keeping the data on the server clean, I disabled the resolvers for mutations, which means that the mutations will not do any create, update or delete operations in the database (and thus return null on the interface).QueryResultIt may take some time to rewrite all types, queries, and resolvers for your existing app. However, a lot of tools exist to help you. For instance, there are tools that translate a SQL schema to a GraphQL schema, including resolvers!With a well-defined schema and resolvers on what to do on each query of the schema, we can mount a /graphql endpoint on our back-end:And we can have a nice-looking GraphiQL interface on our back-end. To make a request without GraphiQL, simply copy the URL of the request, and run it with cURL, AJAX, or directly in the browser. Of course, there are some GraphQL clients to help you build these queries. See below for some examples.This article’s aim is to give you a taste of what GraphQL looks like and show you that it’s definitely possible to try GraphQL without throwing away your REST infrastructure. The best way to know if GraphQL suits your needs is to try it yourself. I hope that this article will make you take the dive.There are a lot of features we haven’t discussed about in this article, such as real-time updates, server-side batching, authentication, authorization, client-side caching, file uploading, etc. An excellent resource to learn about these features is How to GraphQL.Below are some other useful resources:In conclusion, I believe that GraphQL is more than hype. It won’t replace REST tomorrow just yet, but it does offer a performant solution to a genuine problem. It is relatively new, and best practices are still developing, but it is definitely a technology that we will hear about in the next couple of years.GraphQL is a query language and an alternative to REST. It started as an internal project at Facebook.GraphQL merges all your RESTful endpoints into one and uses less network traffic.Hire the top 3% of freelance talent© Copyright 2010 - 2018 Toptal, LLC

Read more

An Angular 5 Tutorial: Step by Step Guide to Your First Angular 5 App

by Sergey Moiseev - Freelance Full-stack Developer @ Toptal Angular is a new version of the AngularJS framework, developed by Google. It comes with a complete rewrite, and various improvements including optimized builds and faster compile times. In this Angular 5 tutorial, we are going to build a notes app from scratch. If you’ve been waiting to learn Angular 5, this tutorial is for you.The final source code for the app can be found here.There are two major versions of the framework: AngularJS (version 1) and Angular (version 2+). Since version 2, Angular is no longer a JavaScript framework, so there’s a huge difference between them, warranting a fundamental name change.It depends. Some developers will tell you that it’s better to use React and build your own components without much additional code. But that may be a problem, too. Angular is a fully integrated framework that allows you to start working on your project quickly without thinking about which libraries to select and how to deal with everyday problems. I think of Angular as being for the front-end, as RoR is for the back-end.If you don’t know TypeScript, don’t be scared. Your JavaScript knowledge is enough to learn TypeScript quickly, and most modern editors are quite effective in helping with that. The most preferable options nowadays are VSCode and any of the JetBrains IntelliJ family (e.g., Webstorm or, in my case, RubyMine). For me, it’s preferable to use a smarter editor than vim, as it will give you an extra heads-up on any mistakes in the code as TypeScript is strongly typed. Another thing to mention is that Angular CLI with its Webpack takes care of compiling TS to JS, so you shouldn’t let the IDE compile it for you.Angular now has its own CLI, or command line interface, which will do most of the routine operations for you. To start using Angular, we have to install it. It requires Node 6.9.0 or higher as well as NPM 3 or higher. We are not going to cover their installation for your system, as it’s better to find up-to-date documentation for installation on your own. Once they are both installed, we are going to install Angular CLI by running the following:After the installation is successful, we can generate a new project by running the ng new command:After that’s done, we can ask our fresh application to start by running ng serve out of its directory:If we navigate our browser to that link, it will be displayed as pictured here:So, what is actually happening here? Angular CLI runs webpack dev server, which renders our app on the next free port (so that you can run multiple apps on the same machine), with live reload. It also watches for every change in the project source and recompiles all changes, after which it asks the browser to reload the open page. So by using Angular CLI, we are already working in a development environment without writing a line of configuration or actually doing anything. But we’re just getting started here…We have our empty app running. Let’s talk about app composition in Angular. If you have some background in AngularJS, you know there were controllers, directives, and components that were somehow like directives but simpler, to allow you to upgrade to Angular 2. For those who don’t have that wonderful experience of having to choose between them and figure out what goes where, don’t worry. It’s mostly just components nowadays. The component is the most basic building block in the Angular world. Let’s look at the code that was generated for us by Angular CLI.First, here’s index.html:It looks like the kind of markup you see every day. But there’s a special tag, app-root. How does Angular make this work, and how can we know what’s happening inside it?Let’s open the src/app directory and see what’s there. You can look at the ng new output form earlier here or open it in your chosen IDE. You will see that we have app.component.ts there with the next bit (this may vary depending on how recent your version of Angular is):@Component(...) here looks like a function call… What is it? This is TypeScript decorator, and we will talk about that a bit later. For now, let’s just try to understand what it’s doing, with passed parameters like selector being used to generate our component declaration. It’s just going a lot of boilerplate work for us and giving back our component declaration in its working form. We don’t have to implement additional code to support any of the decorator’s params. It’s all handled by the decorator. So, generally, we call it factory methods.We already saw app-root in our index.html. Here’s how Angular knows how to find the component corresponding to our tag. Obviously, templateUrl and styleUrls define where Angular should take our markup and CSS from. There are a lot more params for the component decorator, and we are going to use some of them in our new app, but if you want a full reference, you can always look here.Let’s look into that component’s markup:So, aside from embedding the Angular Logo as an SVG, which is pretty neat, this seems like typical everyday markup as well. Aside from one thing (Welcome to {{ title }}!), if we look at our component code again, we will see title = 'app';. So, if you already have some practice in template languages or have worked with AngularJS, it’s pretty obvious what’s happening here. If you don’t know, this is called Angular Interpolation, by which the expression inside the double curly braces is being pulled from our component (you can think of {{ title }} as a simplified form of {{ this.title }}) and displayed on our markup.We’ve now seen all the parts of our auto-generated Angular app that actually take place in the page displayed in our browser. Let’s recap how it actually works: Angular CLI runs Webpack, which is compiling our Angular app into JavaScript bundles and injecting them into our index.html. If we take a look at the actual code in our browser using the inspect feature, we see something like this:Every time we change our code, Angular CLI will recompile, re-inject if needed, and ask our browser to reload the page if it’s open. Angular does it quite quickly, so in most cases, while you’re switching your windows from the IDE to the Browser, it’ll already be reloaded for you.So, let’s start moving toward our goal and, for a start, let’s switch our project from CSS to Sass and open our .angular-cli.json and edit styles and styleExt properties thusly:We also need to add the Sass library to our project and rename styles.css to styles.scss. So to add Sass, I am using yarn:I also want to use Twitter Bootstrap on our project, so I also run yarn add bootstrap@v4.0.0-beta.2 and edit our styles.scss to include this:We need to edit index.html to make our page responsive by changing the meta for our markup to this:And now we can replace app.component.html with this:And now, if we open our browser, we see the following:And that’s it for the boilerplate. Let’s move on to creating our own components.We are going to display notes as cards in our interface, so let’s start by generating our first component, representing the card itself. For that, let’s use Angular CLI by running the following command:If we look into src/app/card/card.component.ts, we can see they are almost the same code, as we have in our AppComponent, with one small difference:I like to mention, at this point, that it’s considered good practice to preface our component selectors with a common prefix, and by default, it’s app-. You can change it to the prefix of your preference by editing the prefix property in .angular-cli.json, so it’s preferable to do so before using ng generate for the first time.So, we have a constructor for our component as well as an ngOnInit function for it. If you’re curious why we did that, you can read about it in Angular’s documentation. But on a basic level, think about these methods like this: A constructor is being called right after the creation of the component, long before data to be passed to it is ready and populated, while ngOnInit only runs after the first cycle of changes to the data, so you have access to your component inputs. We’ll talk about inputs and component communication pretty soon, but for now, let’s just remember that it is preferable to use the constructor for constants, like things that are actually being hard-coded into your component, and ngOnInit for everything that depends on external data.Let’s populate our CardComponent implementation. To start with, let’s just add some markup to it. Default contents for markup are something like this:Let’s replace it with code so it will behave like a card:Now is a good time to display the card component, but this raises additional questions: Who will be responsible for displaying the cards? AppComponent? But AppComponent will be loaded before anything else in the app, so we have to consider it to be tidy and small. We’d better create one more component to take care of storing a list of cards and displaying it on our page.As we described our component’s responsibilities, it is clear that this is supposed to be a Card List Component. Let’s ask Angular CLI to generate it for us:Before we start implementing it, let’s take a look at the thing that we ignored after generating our first component. Angular CLI tells us that it updated app.module.ts for us. We’ve never looked into it, so let’s correct it:Obviously, BrowserModule and NgModule are internal Angular modules. We can read more about both of them in the documentation. AppComponent was here before we started to generate any code, so our new components actually populated the module in two places: First, they are imported from their definition files, and then, they are included in the declarations array of our NgModule decorator. If you are creating a new component from scratch and forget to add a new module to NgModule but try to add it to your markup, your app won’t work with the next error in the JS console:So if your app is not working, for no apparent reason, don’t forget to check your console.Let’s populate our card list component markup (src/app/card-list/card-list.component.html):If we open it in our browser, we’ll see something like this:Currently, we display our cards out of the hard-coded markup. Let’s bring our code one step closer to a real case scenario by moving the hard-coded array of cards into our application:We have our initial list, but still, we need to pass it to the component and render it there. For that, we need to create our first input. Let’s add it to our CardList component:We imported Input from the Angular code and used it as a decorator for class-level variable cards with type Array of objects of any kind. Ideally, we shouldn’t use any, but should use strict typing so that we can define something like an interface card, which will contain all the properties of our card, but we will get that working later—for now, we’re using any just to get a fast and dirty implementation underway.Now, we have our card array in our CardList. How can we display it instead of our current markup? Let’s take a look at the new code in our card list component:This is something new for us, an attribute name that starts from an asterisk. What does it mean? It’s a default convention for naming Angular structural directives. Structural directives control the structure of our template. The asterisk here is actually “syntax sugar,” and you can read further to understand how it works. but for your current example, it’s enough to understand what will happen when we add it to our component. So ngFor a repeater directive and it will repeat our app card for every element in the array of cards. If we look at the browser, we see this next:Something isn’t right; we have our array of cards, but we are getting an empty page.We defined our array of cards on the AppComponent level, but we haven’t passed it to CardList input. Let’s edit our AppComponent template to do that.This syntax—the attribute in square brackets—tells Angular that we would like to one-way bind our component variable cards to our Card List component [cards] input. As soon as we do that, we get this:Of course, we want to display the actual contents of our card array, and for that, we need to pass the card object to the card component as well. Let’s extend our Card List component:And if we look in the browser right now, we’ll get the next error in the JS console: Can't bind to 'card' since it isn't a known property of 'app-card'.. Angular is telling us that we still need to define our input in the Card component. So we can edit thusly:And let’s add our card text property to the Card component template:Let’s see how it works now:Looks fine, but the styling is a little off. Let’s fix that by adding a new style to card.component.css:And now it looks better:Let’s add a New Card Input component that will allow us to add notes:And add this next to its template:Next, add this to the component decorator:And add our new component to the AppComponent template:Let’s take a look at the browser.The problem is that our new component isn’t doing anything. Let’s make it work—let’s start by adding a variable that will hold our new card:How do we populate it with our input? If you’ve worked with AngularJS before, you may know the concept of two-way data binding. Or, you might have seen it in all those fancy AngularJS demos, where you input value to input and it updates the page content for us.Here’s an interesting tidbit: Two-way data binding is no longer with us in Angular. But that doesn’t mean we have lost access to the behavior. We already saw and used [value]="expression", which binds the expression to the input element’s value property. But we also have (input)="expression", a declarative way of binding an expression to the input element’s input event. Together, they can be used thusly:So, every time our newCard.text value changes, it’ll be passed to our component input. And every time the user inputs data into our input and the browser outputs input $event, we assign our newCard.text to the input value.One more thing before we implement it: This input looks like a little much, doesn’t it? Actually, Angular gives us a little syntax sugar for it, which we can use here, so I started from a different angle to explain how this sugar works.This syntax, ([]), called banana in a box or ngModel, is the Angular directive that takes care of getting value out of events and all that. So we can just write simpler code that takes our value and binds it to both the value of the input and our variable in code.Unfortunately, after we added ngModel, we are getting the error, Can't bind to 'ngModel' since it isn't a known property of 'input'.. We need to import ngModel to our AppModule. But from where? If we check the documentation, we can see that it’s in the Angular Forms module. So we need to edit out AppModule thusly:So we have our variable populated, but we still need to send that value to the card list in AppComponent. For communicating data to the component Angular, we must have input. It seems that to communicate data outside the component, we have output, and we use it in the same way we would use input—we import it from the Angular code and use a decorator to define it:But there is more than just output; we also define something called EventEmitter because the component output is supposed to be an event, but we shouldn’t think about it the same way we did those old JavaScript events. They aren’t bubbles. You don’t need to call preventDefault in every event listener. To send data from the component, we should use its payload. So we need to subscribe to the events—how do we do that? Let’s change the AppComponent template:We are also binding an expression to the event onCardAdd, just as we mentioned in our NewCardInput component. Now we need to implement the addCard method on our AppComponent.But we’re still not outputting it from anywhere. Let’s try to make it happen when the user hits the enter key. We need to listen for the DOM keypress event in our component and output the Angular event triggered by that. For listening to DOM events, Angular gives us the HostListener decorator. It’s a function decorator that takes the name of a native event we want to listen for and the function Angular wants to call in response to it. Let’s implement it and discuss how it works:So, if the document:keypress event happens, we check that the key pressed was Enter and our newCard.text has something in it. After that, we can call our addCard method, in which we output Angular onCardAdd with text from our card and reset the card text to an empty string so the user can continue to add new cards without editing the old card’s text.There are a couple of approaches to working with forms in Angular—one is template-driven and we are already using the most valuable part of it: ngModel for two-way binding. But forms in Angular are not only about model values, but also about validity. Currently, we check for validity of NewCardInput in our HostListener function. Let’s move it to a more template-driven form. For that, we can change the template for our component:Here’s another syntax sugar from Angular. The hash #form is a template reference variable that we can use to access our form out of our code. Let’s use it to make sure we actually use the required attribute validation instead of the manual check on value length:One more new decorator is here: ViewChild. Using that, we can access any element marked by template reference value—in this case, our form, and we actually declare it as our Component public variable form, so we can write this.form.valid.Working with template driven forms is absolutely the same as we did before with simple HTML forms. If we need something more complex, there is a different kind of form for that case in Angular: reactive. We’ll cover what they react on after converting our form. For that, let’s add a new import to our AppModule:Reactive forms are defined in code instead of template-driven forms, so let’s change the NewCardInput component code:In addition to importing new modules, some new things are happening here. First of all, we are using dependency injection for FormBuilder on our constructor and building our form with it. The text there is a name of our field, an empty string is the initial value, and Validators.compose obviously allow us to combine multiple validators on a single field. We use .value and .setValue('') to access value for our field.Let’s look at our markup for this new way of working with forms:We are using FormGroupDirective to tell Angular what form group Angular needs to look in for its definition. By using formControlName, we are telling Angular what field in the reactive form we should use.For now, the main difference between the previous approach with template-driven forms and the new approach with reactive forms is in more coding on the reactive side. Is it really worth it, if we don’t need to define the form dynamically?It absolutely is. To understand how it may be helpful, let’s discuss why this approach is called “reactive” in the first place.Let’s start by adding additional code to our New Card Input component constructor:Open the browser and developer tools console, and watch what will happen when we input new value into our input:So what’s actually happening here? We are seeing RxJS in action. Let’s discuss it. I guess you all know at least something about promises and building asynchronous code. Promise handling a single event. We ask the browser to make POST, for example, and it returns us a promise. RxJS operates with Observables, which handle streams of events. Think about that like this: We have just implemented code that is called on every change of our form. If we process user changes with promises, only the first user change will be processed before we need to resubscribe. The Observable, at the same time, is able to process every event in a virtually endless stream of “promises.” We can break that by getting some error along the way or by unsubscribing from the Observable.What is takeWhile here? We are subscribing to our Observables in our components. They are used in different part of our app, so they may be destroyed along the way—for example, when we use components as pages in our routing (and we’ll talk about routing later in this guide). But while the promise in place of the Observable will run only a single time and will be disposed after that, the Observable is built to last as long as the stream is updating and we don’t unsubscribe. So our subscription needs to be unsubscribed (if we are not looking for memory leaks) like this:But in our app, we have a lot of different subscriptions. Do we need to do all of that boilerplate code? Actually, we can cheat and use the takeWhile operator. By using it, we make sure that our stream will stop emitting new values as soon as this.alive becomes false and we just need to set that value in the onDestroy function of our component.Since we’re not building the server side here, we are going to use Firebase for our API. If you actually do have your own API back-end, let’s configure our back-end in development server. To do that, create proxy.conf.json in the root of the project and add this content there:For every request from our app to its host (which, if you remember, is Webpack dev server), the /api route server should proxy the request to http://localhost:3000/api. For that to work, we need to add one more thing to our app configuration; in package.json, we need to replace the start command for our project:Now, we can run our project with yarn start or npm start and get proxy configuration in place. How can we work with the API from Angular? Angular gives us HttpClient. Let’s define our CardService for our current application:So what does Injectable here mean? We already established that Dependency Injection helps us to inject our components with services we use. For getting access to our new service, we need to add it to the provider list in our AppModule:Now we can inject it in our AppComponent, for example:So let’s configure Firebase now, creating a demo project in Firebase and hitting the Add Firebase to your app button. Then, we copy credentials that Firebase shows us into the Environment files of our app, here: src/environments/We need to add it to both environment.ts and environment.prod.ts. And just to give you some understanding of what Environment files are here, they are actually included in the project on compilation phase, and .prod. the part being defined by the --environment switch for ng serve or ng build. You can use values from that file in all parts of your project and include them from environment.ts while Angular CLI takes care of providing content from the corresponding environment.your-environment.ts.Let’s add our Firebase support libraries:And now let’s change our CardService to support Firebase:We see something interesting here, on the first model for the card being imported. Let’s take a look at its composition:So we are structuring our data with classes and, aside from our text, we add key$ from Firebase. Let’s change our AppComponent to work with that service:What is cards$? We mark our observable variables by adding $ to them to make sure we treat them as we should. Let’s add our cards$ to the AppComponent template:In return, we get this error in the console:Why so? We are getting observables from the Firebase. But our *ngFor in the CardList component waits for the array of objects, not observable of such arrays. So we can subscribe to that observable and assign it to a static array of cards, but there is a better option:The async pipe, which is practically another syntax sugar that Angular gives to us, does the same thing we discussed—subscribe to the Observable and return its current value as a result of evaluation of our expression.Let’s talk about our application state, by which I mean all properties of our application that define its current behavior and state literally. State is a single, immutable data structure—at least the way Ngrx implements it for us. And Ngrx is an “RxJS powered state management library for Angular applications, inspired by Redux.”Ngrx is inspired by Redux. “Redux is a pattern for managing application state.” So it’s more like set of conventions (for those of you who ever heard of convention over configuration in Ruby on Rails, you will see some similarities a bit later) that allow us to answer the question of how our application should decide it needs to display some interface element (like a collapsible sidebar) or where it is supposed to store its session state after it receives it from the server.Let’s see how this is achieved. We talked about State and its immutability, which means we can’t change any of its properties after creating it. This makes it all but impossible to store our application state in our State. But not completely—every single state is immutable, but the Store, which is our way of accessing State, is actually an Observable of the states. So State is a single value in a stream of Store values. In order to change the app’s state, we need to make some Actions that will take our current State and replace it with a new one. Both are immutable, but the second is based on the first, so instead of mutating values on our State, we create a new State object. For that, we use Reducers as pure functions, meaning that for any given State and Action and its payload reducer, it will return the same state as in any other call of that reducer function with same parameters.Actions consist of action type and optional payload:For our task, let’s view how the action for adding a new card could be:Let’s see a reducer for that:This function is being called for every new Action event. We’ll cover Action dispatching a bit later. For now, let’s say that if we dispatch our ADD_CARD action, it’ll get into that case statement. What is happening there? We are returning our new State based on our previous State by using TypeScript spread syntax, so we don’t have to use something like Object.assign in most cases. We never should change our state outside of those case statements, or it will make life miserable as we waste time searching for the reason why our code is behaving unpredictably.Let’s add Ngrx to our application. For that, let’s run next in our console:Now, add our Action definition (app/actions/cards.ts):And our Reducer definition (app/reducers/cards.ts):Here we can see how you can use spreads and native TypeScript functions like map to drop the element off our list.Let’s go one step further and make sure that if our application state will contain more than one type of data, we are composing it from a separate isolated state for each kind. For that, let’s use module resolution using (app/reducers/index.ts):We also include a logger for our Ngrx in the development environment and create a selector function for our card array. Let’s include it in our AppComponent:Now, we see how we dispatch our actions using our store. But this code is still non-usable, as we don’t include our reducers (reducer and metaReducer) into our app. Let’s do it by changing our AppModule:And now it’s working. Kind of. Remember, we happen to have Firebase integrated into our App. Now it’s lost due to the highly maintainable Ngrx store. That is, it is stored nowhere. We can use something like ngrx-store-localstorage to store our data the browser’s localStore, but how about working with APIs? Maybe we can add our previous API integration into our Reducer? But we can’t, as our Reducer function is supposed to be a pure function. So, “evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices”… What can we do with that? The answer is actually right in that definition. Side-effects of Ngrx to the rescue.So what is a side effect? Its piece of code that catches our Actions more or less the same way as our reducers do, but instead of changing something in our state, they actually send API requests and, on the result, dispatch new Actions. As always, it’s simpler to show you than to tell you. Let’s make our new configuration support Firebase. For that, let’s install the effects module:Now we will add new actions to our Card Actions for loading support (src/app/actions/cards.ts):So we have three new actions, one for loading the card list and two for dealing with successful and unsuccessful responses. Let’s implement our effects (src/app/effects/cards.ts):So we have injectable CardsEffects, which use the @Effect decorator for defining effects on top of our Actions and filtering only necessary actions by using the ofType operator. You may use ofType to create an effect that will be fired on multiple action types. But for now, we only need two out of our three actions. For the Load action, we are transforming every action into a new observable on the result of our getCardList method call. In the case of success, the observable will be mapped to a new action LoadSuccess with a payload of our request results, and in the case of error, we’ll return a single ServerFailure action (mind the of operator there—it converts a single value or array of values to the observable).So our Effects dispatch new Actions after making something that depends on the external system (our Firebase, to be precise). But within the same code, we see another effect, which handles the ServerFailure action using the decorator parameter dispatch: false. What does this mean? As we can see from its implementation, it also maps our ServerFailure action to its payload, and then displays this payload (our server error) to console.log. Clearly, in that case, we should not change state contents, so we don’t have to dispatch anything. And that’s how we make it work without any need for empty actions.So, now that we’ve covered two of our three actions, let’s move on to LoadSuccess. From what we know so far, we are downloading a list of cards from the server and we need to merge them into our State. So we need to add it to our reducer (src/app/reducers/cards.ts):So same story as before, we open our object and card array in it by using the spread operator and join it with the spread payload (cards from the server, in our case). Let’s add our new Load action to our AppComponent:That should load our cards from Firebase. Let’s take a look at the browser:Something is not working. We are clearly dispatching the Action, as can be seen from our logs, but no server request is here for us. What’s wrong? We forgot to load our Effects to our AppModule. Let’s do that:And now, back to the browser…Now it’s working. So that’s how you integrate effects into loading data from the server. But we still need to send it back there on our card creation. Let’s make that work as well. For that, let’s change our CardService createCard method:And add an effect for the Adding card:So, if the card is to be created, it’ll get $key from Firebase and we’ll merge it into our card array. We also need to remove the case cards.ADD: branch from our reducer. Let’s try it in action:For some reason, we are getting duplicated data on the card add operation. Let’s try to figure out why. If we look closely at the console, we’ll see two LoadSuccess actions first being dispatched with our new card as it is supposed to be, and the second one is being dispatched with both of our cards. If not in effects, where in our action is it being dispatched?Our Load effect on cards has this code:And our getCardsList is observable. So when we add a new card to our card collection, it is output. So either we don’t need to add that card on our own, or we need use a take(1) operator in that pipe. It’ll take a single value and unsubscribe. But having live subscription seems more reasonable (presumably, we will have more than one user in the system), so let’s change our code to deal with the subscription.Let’s add a non-dispatching element to our effect:Now we only need to change the reducer LoadSuccess to replace cards, not combine them:And now it’s working as it should:You can implement remove action the same way now. As we get data out of that subscription, you only have to implement the Remove effect. But I will leave that to you.Let’s speak about our application composition. What if we need an About page in our application? How can we add that to our current codebase? Obviously, the page is supposed to be a component (as anything else in Angular, mostly). Let’s generate that component.And add the next markup to it:So now, we have our About page. How we can access it? Let’s add some more code to our AppModule:What is MainComponent here? For now, just generate it the same way we did with AboutComponent and we’ll populate it later. As for route structure, it more or less speaks for itself. We define two routes: /cards and /about. And we make sure that empty path redirects for /cards.Now let’s move our cards handling code to MainComponent:And let’s remove it from AppComponent:And from markup as well:As you can see, we added some more things. First of all, we added router directives for RouterLinkActive, which is setting a class when our route is active, and routerLink, which replaces href for us. And here is routerOutlet, which tells Router where to display its contents on a current page. So, combining those, we now have the menu on every page, along with two pages with different content:For more details, please read the Router Guide.As our application grows, we may start thinking of optimization. For example, what if we like to load the About component for default and only load additional components after the user implicitly asks for it by clicking on the Cards link. For that, we can use lazy loading of modules. Let’s start by generating CardsModule:By using the flat flag, we are telling Angular to not create the separate directory for our module. Let’s transfer all card-related things into our new module:Previously, we saw a lot of forRoot calls in our import, but here, we call for a lot of forFeature or forChild. That’s how we tell our components that we are extending our configuration, not creating it from scratch.Let’s see what is still in our AppModule:Here, we still define EffectsModule.forRoot or it won’t work in our loaded module (as it will be nowhere to add on lazy load). We also see new syntax here for the router loadChildren that tells our router to lazy load CardsModule located in the ./cards.module file when we ask for the cards route. And we include meta reducers from the new ./reducers/root.ts file—let’s take a look at it:On a root level, we currently don’t have any state, but we still need to define the empty state so we can extend it in the progress of lazy loading. That also means that our state of cards has to be defined somewhere else, and for this example, we define it in src/app/reducers/index.ts:So we extend our root state by cards key. And that gives us key nesting duplication at the end (as both a module and an array called cards).If we open our app now and look into the network tab of the developer console, we’ll see that cards.module.chunk.js is being loaded only after we click on the /cards link.So let’s build our app for production use. And for that, let’s run the build command:So what’s happening here? We are building our application to static assets that could be served from any web server (if you want to serve from subdirectory ng build, have the option --base-href ). By using -prod, we are telling AngularCLI that we need the production build. And --aot is telling it that we like to have ahead-of-time compilation. In most cases, we prefer that, as it allows us to get the smaller bundle and faster code. Also, keep in mind that AoT is way too strict on your code quality, so it may produce errors that you haven’t seen before. Run the build earlier so it’s easier to fix.Another reason to build our app is how Angular handles i18n or, speaking in plain terms, internationalization. Instead of dealing with it at runtime, Angular does it at compilation. Let’s configure it for our app. For that, let’s add the i18n attribute to our AboutComponent.By using that, we are telling the Angular compiler that the tag’s contents need to be translated. It’s not the Angular directive, and it is removed by the compiler in the process of compilation and replaced by the translation for a given language. So we marked our first translated message, but what next? How can we actually translate that? For that, Angular offers us the ng xi18n command:So we have a translation file mapping out our messages to their actual locations in the source code. Now, we can give the file to PhraseApp. Or, we can just add our translation manually. For that, let’s create a new file in src, messages.ru.xlf:We now can serve our app—in Russian, for example—by running this command ng serve --aot --locale=ru --i18n-file=src/messages.ru.xlf. Let’s see if it works:Now, let’s automate our build script so we can make our app build in two languages on every production build and call its corresponding directories en or ru. For that let’s add the build-i18n command to the scripts section of our package.json:Now let’s package our app for production use, and use Docker for that. Let’s start with Dockerfile:So we are using a multistage build for our app with a Node-based image, and then we build the server package with an Nginx-based image. We also use Gulp to compress our artifacts, as Angular CLI no longer does it for us. I find that strange, but okay, let’s add Gulp and compression scripts.Lets add gulpfile.js in our app root:Now we only need our Nginx config to build our container. Let’s add it to nginx/default.conf:So we are serving our build application from directories en or ru and by default, we are redirecting from root URL to /en/.Now we can build our app by using the docker build -t app . command:And then we can serve it using Docker from a local machine by running docker run -it -p 80:80 app. And it’s working:Mind the /en/ in URL.Congratulations on completing this tutorial. You can now join the ranks of other Angular developers. You’ve just created your first Angular app, used Firebase as a backend and served it via Nginx in a Docker container.As with any new framework, the only way to get good at it is to keep practicing. Hopefully you’ve come to understand just how powerful Angular is. When you’re ready to proceed, the Angular documentation is a wonderful resource and comes with a whole section on advanced techniques.If you feel like taking on something more advanced, try Working with Angular 4 Forms: Nesting and Input Validation by fellow Toptaler Igor Geshoki.We use it to develop rich interface client-side applications like single-page applications and mobile applications. The main advantage of Angular is getting a fully integrated web framework that offers its own in-box solutions for building components, routing, and working with remote APIs.The main advantage of using Angular is getting a fully integrated web framework that offers its own in-box solutions for building components, routing, and working with remote APIs.Modules separate the scope of declarations in them. That allows us to build multiple independent modules for our app and use lazy loading for the modules. The purpose of a module is to declare everything that is used in this module and allow Angular to do ahead-of-time compilation for it.Angular is no longer an MVC framework, unlike AngularJS. It’s a component-based framework. Components take the role of controllers here, but only on a very simplified level of abstraction. RxJS is the Reactive Extensions library for JavaScript, which allows us to operate with Observables, which are streams of events that replace stand-alone promises for us. NgRX is a pattern for managing application states. It’s an RxJS-powered state management library for Angular applications. It allows us to have a single application state to wire all components together and provide predictable and consistent behavior for our app. Hire the top 3% of freelance talent© Copyright 2010 - 2018 Toptal, LLC

Read more

Which languages you should learn first

There's a lot to learn when it comes to coding. How do you know where to start? Should you learn HTML or JavaScript? What's the difference between Python and Ruby? What are "client-side" and "server-side" languages, "front end" and "back end," and how are they different? Hopefully this quick post will help you choose the language best suited for what you want to do. Coding is a tool: pick the language that suits your needs Similar to spoken languages, the answer to the question of "which coding language should I learn" depends on your context, and what you want to do with the language. If you wanted to move to France, you should probably learn French. Coding languages can vary a lot in what they can do and how they work… and that means some are better suited to certain tasks than others. The following is a breakdown of how different languages are used in order to build websites; even if building sites isn't your goal, knowing how that process works will help you figure out your coding path. To edit webpages If you're interested in creating a static website or a single webpage, you should start with HTML and CSS. HTML stands for Hyper Text Markup Language and describes the structure of webpages. CSS stands for Cascading Style Sheets, and controls their appearance — for example, the font color or the position of text on the page. To make them interactive If you want to give your website behavior—think automatic Twitter updates, your Facebook notifications, or the ability to drag and drop elements of your LinkedIn profile—then you'll want to learn JavaScript and jQuery. JavaScript is a frontend, or "client-side" language which means it runs on the web browser of the person visiting your site. jQuery is a library of specific JavaScript tools designed to make website interaction more awesome. To store user information If you want to develop a full-blown web app that lets users log in and saves information for them (such as tweets, Facebook posts, or Codecademy badges), you'll want to learn a backend, or "server-side" language like PHP, Python, Ruby or JavaScript (it's ambidextrous). These languages run on the computer where the website code lives, also called the server. You can accomplish the same things and build the same kinds of projects with each of them, so go ahead and pick your favorite! Choosing a server-side language is often a matter of personal preference, even for professional developers. Codecademy courses are a great way to try out different languages and see which ones you prefer and for what reasons. Many languages work on similar principles, like object-orientation, so once you've learned one you could find yourself having an easier time learning another - don't be afraid to experiment! Putting it together In order to make a fully-functioning and beautiful website with interactivity and complex functionality, you'll need to learn both frontend and backend (or client-side and server-side) and put them together. That's why one of the most popular routes that users take on Codecademy is learning what they need to build a website: HTML, CSS, JavaScript, jQuery, and a server-side language (typically in that order). Even if your eventual goal is not to build websites (if you want to build an iOS app, or to become a data scientist), having a basic understanding of how websites work is a great way to get exposure to how to make things with code. Once you've done this, you'll find that you have the experience you need to make some intelligent decisions about how to move forward. The bottom line There are many people you can ask for further advice, from our advisors on Codecademy Pro through to your fellow community members right here on this forum… but answering the question of what languages you should learn is something that is ultimately down to you. We hope that you find Codecademy to be a fun place to experiment with different coding languages and see which ones you like best! Which language will you start with?

Read more