<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Valentine Oragbakosi on Medium]]></title>
        <description><![CDATA[Stories by Valentine Oragbakosi on Medium]]></description>
        <link>https://medium.com/@oragbakosi13400?source=rss-c4e6bc2d8b8b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*YyOfZt6EWrXyb4-VWHUt-A.gif</url>
            <title>Stories by Valentine Oragbakosi on Medium</title>
            <link>https://medium.com/@oragbakosi13400?source=rss-c4e6bc2d8b8b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 23:50:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oragbakosi13400/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Writing a Node js package manager]]></title>
            <link>https://medium.com/@oragbakosi13400/writing-a-node-js-package-manager-7e6b2389a634?source=rss-c4e6bc2d8b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e6b2389a634</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[bonnie]]></category>
            <category><![CDATA[package-manager]]></category>
            <dc:creator><![CDATA[Valentine Oragbakosi]]></dc:creator>
            <pubDate>Tue, 20 Jul 2021 12:30:02 GMT</pubDate>
            <atom:updated>2021-07-20T12:30:02.649Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is basically my experience writing a Node js package manager using the Rust programming language. The decisions I took, the challenges I faced and the fun I had 😄. You can see the repo <a href="https://github.com/Valentine-Mario/bonnie/tree/installation">here</a>. This sub-project was intended to be part of a command aliasing tool I had contributed to in the past called <a href="https://github.com/arctic-hen7/bonnie">bonnie</a></p><p>The goal was to make the package manager work as much as possible as <strong>npm</strong> or <strong>yarn </strong>but instead of a package.json file for configurations, it would instead use a <a href="https://en.wikipedia.org/wiki/TOML"><strong>TOML </strong></a>file which is easier to read as the name suggest.</p><p><strong>Challenge 1:</strong></p><p>The first challenge was basically straightforward, it involved reading inputs from either the command line arg or the <strong>bonnie.toml</strong> file. Luckily, Rust has a way to easily read and parse command line arg, which did not bring much of a challenge.</p><pre>use std::env;</pre><pre>fn main() {</pre><pre>//read arg from cmd line and append them all to a vector</pre><pre>let prog_args: Vec&lt;String&gt; = env::args().collect();<br></pre><pre>//if the first work is install or i, run  this bock</pre><pre>if prog_args.get(1) == Some(&amp;String::from(&quot;install&quot;))</pre><pre>|| prog_args.get(1) == Some(&amp;String::from(&quot;i&quot;)){</pre><pre>//get the rest if the inputs<br>let dependecy_list = prog_args.get(2..prog_args.len());<br>println!(&quot;{:?}&quot;, dependecy_list)</pre><pre>}</pre><pre>}</pre><p>With this block of code, we can now parse command line args and get the list of dependencies. if you run <strong>cargo run install express mongodb </strong>you should see a list of strings containing express and mongodb printed out. Now we have that out of the way, let’s create the alternative of reading and parsing the TOML file.</p><p>Just like <strong>npm</strong> when someone runs <strong>npm install </strong>with zero args, it reads the <strong>package.json</strong> file and installs the dependencies and devDependencies. So we need to find a way to accommodate that. <a href="https://crates.io/crates/toml">toml crate</a> to the rescue 😄. With this crate, I was able to parse the TOML file and retrieve the dependencies and devDependencies.</p><p>Example of a bonnie.toml file</p><pre>[scripts]</pre><pre>build = &quot;cargo build&quot;</pre><pre>test = &quot;cargo test&quot;</pre><pre>[dependencies]</pre><pre>express=&quot;4.17.1&quot;</pre><pre>imagizer-javascript = &quot;1.9.1&quot;</pre><pre>mongodb = &quot;4.0.0&quot;</pre><p>So I wrote a function that does the parsing. For now, I considered only dependencies</p><pre>//struct to hold dependencies hash map<br>#[derive(Deserialize, Debug)]</pre><pre>pub struct Dependencies {</pre><pre>pub dependencies: HashMap&lt;String, String&gt;,</pre><pre>}<br></pre><pre>pub fn parse_dependencies(cfg_string: String) -&gt; Result&lt;Dependencies, String&gt; {</pre><pre>//read toml file from source and target dependency key<br>let raw_cfg: Result&lt;Dependencies, toml::de::Error&gt; = toml::from_str(&amp;cfg_string);</pre><pre>let raw_cfg = match raw_cfg {</pre><pre>Ok(raw_cfg) =&gt; raw_cfg,</pre><pre>Err(_) =&gt; return Err(String::from(&quot;Please create a dependecy key in config&quot;)),</pre><pre>};</pre><pre>Ok(raw_cfg)</pre><pre>}</pre><p>This simple function would take in the path of the bonnie config, parse the TOML, and return a struct of dependency hashmap with the structure of <strong>Hashmap&lt;package, version&gt;</strong>. That seems to solve the first challenge 🤘🏻</p><p><strong>Challenge 2:</strong></p><p>Next, my new challenge was how to handle installation from different sources. In this case the command line and the bonnie config file. I decided to use a simple approach which is if the command only has <strong>install</strong> as a keyword, read the bonnie config, and parse it. Else read the additional args and add them to a vector.</p><p>This basically would mean I would have to create 2 new functions. One for handling installation from the command line, the other for bonnie config.</p><pre>use std::env;</pre><pre>fn main() {</pre><pre>//read arg from cmd line and append them all to a vector</pre><pre>let prog_args: Vec&lt;String&gt; = env::args().collect();</pre><pre>//if the first work is install or i, run  this bock</pre><pre>if prog_args.get(1) == Some(&amp;String::from(&quot;install&quot;))</pre><pre>|| prog_args.get(1) == Some(&amp;String::from(&quot;i&quot;)){</pre><pre>if prog_args.get(2) == None {</pre><pre><em>//install dependencies from toml config when no arg is supplied</em></pre><pre>let cfg_string = get_cfg(&amp;cfg_path);</pre><pre>install_dependencie_from_toml(cfg_string.unwrap());</pre><pre>} else {</pre><pre><em>//install dependencies from args</em></pre><pre>let dependecy_list = prog_args.get(2..prog_args.len());</pre><pre>install_dependencie_from_arg(dependecy_list.unwrap());</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>Now, let’s work on these 2 different functions. Here comes the hard work 😞</p><p><strong>Challenge 3:</strong></p><p>The next challenge was getting the latest version of packages supplied via the command line. Thankfully npm has an open-source API that we can use to retrieve this. Here comes <a href="https://crates.io/crates/tokio"><strong>tokio</strong></a><strong> </strong>🕺💃</p><pre>pub async fn get_latest_version(dependency: &amp;String) -&gt; Result&lt;(&amp;String, String), String&gt; {</pre><pre>//format url to accept dependency name<br>let url = format!(&quot;https://registry.npmjs.org/{}&quot;, dependency);</pre><pre>//make api call using reqwest<br>let reponse = reqwest::get(url).await.unwrap();</pre><pre>//parse result</pre><pre>let object: std::result::Result&lt;serde_json::Value, reqwest::Error&gt; =</pre><pre>reponse.json::&lt;serde_json::Value&gt;().await;</pre><pre>match object {</pre><pre>Ok(object) =&gt; {</pre><pre>let data = &amp;*object.get(&quot;dist-tags&quot;).unwrap();</pre><pre>//return tuplue of dependecy and latest version<br>return Ok((dependency, String::from(data[&quot;latest&quot;].as_str().unwrap())));</pre><pre>}</pre><pre>Err(_) =&gt; return Err(String::from(&quot;Error getting latest version of package&quot;)),</pre><pre>};</pre><pre>}</pre><p>Notice that this is an async function, So I had to use <strong>tokio </strong>to make the main function also async. We don’t have to worry about doing this for packages stated in the bonnie config file as they already have a version specified.</p><p><strong>Challenge 4</strong>:</p><p>This next challenge was probably one of the biggest I faced. Since dependencies also have their own dependencies and those dependencies also have their own dependencies, and it keeps going (recursively). I have been faced with either download the dependency as I meet them when recursively getting all related dependencies, or store the dependencies and all related dependencies in a hash map. I went for the latter approach and stored the dependencies, and all related dependencies in a huge hash map to be used later with the structure <strong>HashMap&lt;package, version&gt;.</strong></p><p>But I also decided to split this into 2 different functions. 1 to get the immediate dependencies of the package, the other to get all other nested dependencies of the immediate dependencies.</p><pre>//get dependencies and store them in a hash map<br>pub async fn get_dependencies_and_dev_dependencies(</pre><pre>dependency: &amp;String,</pre><pre>version: &amp;String,</pre><pre>) -&gt; Result&lt;HashMap&lt;std::string::String, std::string::String&gt;, String&gt; {</pre><pre>let url = format!(&quot;https://registry.npmjs.org/{}/{}&quot;, dependency, version);</pre><pre>let mut all_dependencies: HashMap&lt;std::string::String, std::string::String&gt; = HashMap::new();</pre><pre>let reponse = reqwest::get(url).await.unwrap();</pre><pre>let object: std::result::Result&lt;serde_json::Value, reqwest::Error&gt; =</pre><pre>reponse.json::&lt;serde_json::Value&gt;().await;</pre><pre>match object {</pre><pre>Ok(object) =&gt; {</pre><pre>let dependencies = object.get(&quot;dependencies&quot;);</pre><pre><em>// let dev_dependencies = object.get(&quot;devDependencies&quot;);</em></pre><pre>match dependencies {</pre><pre>Some(dependency_value) =&gt; {</pre><pre>let dependency_map = dependency_value.as_object().unwrap();</pre><pre>for (key, value) in dependency_map.iter() {</pre><pre>all_dependencies</pre><pre>.insert(String::from(key), String::from(value.as_str().unwrap()));</pre><pre>}</pre><pre>}</pre><pre>None =&gt; {}</pre><pre>}</pre><pre>return Ok(all_dependencies);</pre><pre>}</pre><pre>Err(_) =&gt; return Err(String::from(&quot;Error getting package&quot;)),</pre><pre>};</pre><pre>}</pre><p>After this is run, it iterates over the dependencies and retrieves all other nested dependencies.</p><pre>#[async_recursion]</pre><pre>pub async fn get_related_dependencies(</pre><pre>dependency: &amp;String,</pre><pre>version: &amp;String,</pre><pre>) -&gt; Result&lt;HashMap&lt;std::string::String, std::string::String&gt;, String&gt; {</pre><pre>let url = format!(&quot;https://registry.npmjs.org/{}/{}&quot;, dependency, version);</pre><pre>let mut all_dependencies: HashMap&lt;std::string::String, std::string::String&gt; = HashMap::new();</pre><pre>let reponse = reqwest::get(url).await.unwrap();</pre><pre>let object: std::result::Result&lt;serde_json::Value, reqwest::Error&gt; =</pre><pre>reponse.json::&lt;serde_json::Value&gt;().await;</pre><pre>match object {</pre><pre>Ok(object) =&gt; {</pre><pre>let dependencies = object.get(&quot;dependencies&quot;);</pre><pre>match dependencies {</pre><pre>Some(dependency_value) =&gt; {</pre><pre>let dependency_map = dependency_value.as_object().unwrap();</pre><pre>if dependency_map.len() &gt; 0 {</pre><pre>for (key, value) in dependency_map.iter() {</pre><pre>all_dependencies</pre><pre>.insert(String::from(key), String::from(value.as_str().unwrap()));</pre><pre>//recusion occurs here</pre><pre>get_related_dependencies(key, &amp;String::from(value.as_str().unwrap()))</pre><pre>.await?;</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>None =&gt; {}</pre><pre>}</pre><pre>return Ok(all_dependencies);</pre><pre>}</pre><pre>Err(_) =&gt; return Err(String::from(&quot;Error getting package&quot;)),</pre><pre>}</pre><pre>}</pre><p>So we now have 2 big hash maps. One with immediate dependencies and the other with related nested dependencies. 🤘🏻👏</p><p><strong>Challenge 5:</strong></p><p>Now that we have gotten all the dependencies and nested dependencies, we need to download them and unzip them inside a node_modules folder. But before then, we need to get the download link. Fortunately, we already have all the nested packages and version numbers in a hash map. So we can simply iterate the hash map, and return a tuple of package and link</p><pre>pub async fn get_tarball_download_link_and_name(</pre><pre>dependency: &amp;String,</pre><pre>version: &amp;String,</pre><pre>) -&gt; Result&lt;(String, String), String&gt; {</pre><pre>let url = format!(&quot;https://registry.npmjs.org/{}/{}&quot;, dependency, version);</pre><pre>let reponse = reqwest::get(url).await.unwrap();</pre><pre>let object: std::result::Result&lt;serde_json::Value, reqwest::Error&gt; =</pre><pre>reponse.json::&lt;serde_json::Value&gt;().await;</pre><pre>match object {</pre><pre>Ok(object) =&gt; {</pre><pre>let data = &amp;object.get(&quot;dist&quot;);</pre><pre>match data {</pre><pre>Some(data) =&gt; {</pre><pre>let name = &amp;object.get(&quot;name&quot;);</pre><pre>match name {</pre><pre>Some(name) =&gt; {</pre><pre>return Ok((</pre><pre>String::from(data[&quot;tarball&quot;].as_str().unwrap()),</pre><pre>(String::from(name.as_str().unwrap())),</pre><pre>));</pre><pre>}</pre><pre>None =&gt; {</pre><pre>return Ok((</pre><pre>String::from(data[&quot;tarball&quot;].as_str().unwrap()),</pre><pre>(String::from(dependency)),</pre><pre>));</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>None =&gt; return Err(String::from(&quot;Error getting download link&quot;)),</pre><pre>}</pre><pre>}</pre><pre>Err(_) =&gt; return Err(String::from(&quot;Error getting download link&quot;)),</pre><pre>};</pre><pre>}</pre><p>Next, we download and extract</p><pre>//downlaod the zip package inside the node_module<br>pub async fn download_package(url: (String, String)) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {</pre><pre>check_node_module().unwrap_or_else(|error| {</pre><pre>eprintln!(&quot;error creating node_modules dir {}&quot;, error);</pre><pre>std::process::exit(1);</pre><pre>});</pre><pre>let response = reqwest::get(&amp;url.0).await?;</pre><pre>let url_parse = Url::parse(&amp;url.0.as_str()).unwrap();</pre><pre>let filename = url_parse.path().split(&quot;/&quot;).last().unwrap();</pre><pre>let write_path = format!(&quot;{}/{}&quot;, NODE_MODULES, filename);</pre><pre>let mut file = std::fs::File::create(&amp;write_path)?;</pre><pre>let mut content = Cursor::new(response.bytes().await?);</pre><pre>std::io::copy(&amp;mut content, &amp;mut file)?;</pre><pre>exract(&amp;write_path, &amp;url.1).unwrap();</pre><pre>Ok(())</pre><pre>}</pre><pre>//check if node_modules folder exist else create one<br>fn check_node_module() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {</pre><pre>let exist = Path::new(NODE_MODULES).exists();</pre><pre>if !exist {</pre><pre>fs::create_dir(NODE_MODULES)?;</pre><pre>}</pre><pre>Ok(())</pre><pre>}</pre><pre><br>//extract the package and delete the zip package</pre><pre>fn exract(zip_file: &amp;str, folder: &amp;String) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {</pre><pre>let tar_gz = File::open(zip_file)?;</pre><pre>let tar = GzDecoder::new(tar_gz);</pre><pre>let mut archive = Archive::new(tar);</pre><pre>let write_path = format!(&quot;{}/{}&quot;, NODE_MODULES, folder);</pre><pre>archive.unpack(&amp;write_path)?;</pre><pre>let from = format!(&quot;{}/package/&quot;, &amp;write_path);</pre><pre>copy_dir(&amp;from, write_path)?;</pre><pre>fs::remove_dir_all(&amp;from)?;</pre><pre>fs::remove_file(zip_file)?;</pre><pre>Ok(())</pre><pre>}</pre><p>The hard part is almost complete 🧟🎃</p><p><strong>Challenge 6:</strong></p><p>Remember when I said different methods handle the installation for the command line and bonnie config, let’s put it all together. But also remember that when installing via command line, the package and version number is written to the config file after successful download right? Here I made use of <a href="https://docs.rs/toml_edit/0.2.1/toml_edit/">toml_edit</a>. After installation via command line is complete, this small piece of code is run</p><pre>let cfg_path = get_cfg_path(env::var(&quot;BONNIE_CONF&quot;));</pre><pre>let contents = fs::read_to_string(&amp;cfg_path)</pre><pre>.expect(&quot;Something went wrong reading the file&quot;);</pre><pre>let mut doc = contents.parse::&lt;Document&gt;().expect(&quot;invalid toml document&quot;);</pre><pre>doc[&quot;dependencies&quot;][&amp;package]=value(version);</pre><pre>doc[&quot;dependencies&quot;].as_inline_table_mut().map(|t| t.fmt());</pre><pre>fs::write(&amp;cfg_path, doc.to_string()).unwrap();</pre><p>This would append the package and version in the dependency key of the bonnie config.</p><p>Also, note that I did not take into consideration pieces of stuff like ~ and ^ in the version number which of course had their meaning because I wanted to keep it simple for now.</p><p>Now, let’s bring it all together</p><pre>pub async fn install_dependencie_from_arg(args: &amp;[std::string::String]) {</pre><pre>for dependency in args {</pre><pre>let (package, version) = get_latest_version(dependency).await.unwrap();</pre><pre>let version = version.replace(&quot;~&quot;, &quot;&quot;);</pre><pre>let version = version.replace(&quot;^&quot;, &quot;&quot;);</pre><pre>println!(&quot;getting packages...&quot;);</pre><pre>let mut dep = get_dependencies_and_dev_dependencies(package, &amp;version)</pre><pre>.await</pre><pre>.unwrap();</pre><pre>println!(&quot;{:?}&quot;, dep);</pre><pre>for (k, v) in dep.clone() {</pre><pre>let v = v.replace(&quot;~&quot;, &quot;&quot;);</pre><pre>let v = v.replace(&quot;^&quot;, &quot;&quot;);</pre><pre>let a = get_related_dependencies(&amp;k, &amp;v).await.unwrap();</pre><pre>println!(&quot;{:?}&quot;, a);</pre><pre>for (key, value) in a {</pre><pre>dep.insert(key, value);</pre><pre>}</pre><pre>}</pre><pre>for (k, v) in dep.clone() {</pre><pre>println!(&quot;downloading dependency {} ...&quot;, k);</pre><pre>let v = v.replace(&quot;~&quot;, &quot;&quot;);</pre><pre>let v = v.replace(&quot;^&quot;, &quot;&quot;);</pre><pre>let link = get_tarball_download_link_and_name(&amp;k, &amp;v).await;</pre><pre>match link {</pre><pre>Ok(link) =&gt; {</pre><pre>download_package(link).await.unwrap();</pre><pre>}</pre><pre>Err(err) =&gt; {</pre><pre>eprintln!(&quot;{}&quot;, err)</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>println!(&quot;downloading dependency {} ...&quot;, package);</pre><pre>let link = get_tarball_download_link_and_name(&amp;package, &amp;version).await;</pre><pre>match link {</pre><pre>Ok(link) =&gt; {</pre><pre>download_package(link).await.unwrap();</pre><pre><em>//write to bonie toml</em></pre><pre>let cfg_path = get_cfg_path(env::var(&quot;BONNIE_CONF&quot;));</pre><pre>let contents = fs::read_to_string(&amp;cfg_path)</pre><pre>.expect(&quot;Something went wrong reading the file&quot;);</pre><pre>let mut doc = contents.parse::&lt;Document&gt;().expect(&quot;invalid toml document&quot;);</pre><pre>doc[&quot;dependencies&quot;][&amp;package]=value(version);</pre><pre>doc[&quot;dependencies&quot;].as_inline_table_mut().map(|t| t.fmt());</pre><pre>fs::write(&amp;cfg_path, doc.to_string()).unwrap();</pre><pre>}</pre><pre>Err(err) =&gt; {</pre><pre>eprintln!(&quot;{}&quot;, err)</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>And the function to install from bonnie.toml file</p><pre>pub async fn install_dependencie_from_toml(value: String) {</pre><pre>let dep=parse_dependencies(value).unwrap();</pre><pre>for (package, version) in dep.dependencies {</pre><pre>let version = version.replace(&quot;~&quot;, &quot;&quot;);</pre><pre>let version = version.replace(&quot;^&quot;, &quot;&quot;);</pre><pre>println!(&quot;getting packages...&quot;);</pre><pre>let mut dep = get_dependencies_and_dev_dependencies(&amp;package, &amp;version)</pre><pre>.await</pre><pre>.unwrap();</pre><pre>for (k, v) in dep.clone() {</pre><pre>let v = v.replace(&quot;~&quot;, &quot;&quot;);</pre><pre>let v = v.replace(&quot;^&quot;, &quot;&quot;);</pre><pre>let a = get_related_dependencies(&amp;k, &amp;v).await.unwrap();</pre><pre>println!(&quot;{:?}&quot;, a);</pre><pre>for (key, value) in a {</pre><pre>dep.insert(key, value);</pre><pre>}</pre><pre>}</pre><pre>for (k, v) in dep.clone() {</pre><pre>println!(&quot;downloading dependency {} ...&quot;, k);</pre><pre>let v = v.replace(&quot;~&quot;, &quot;&quot;);</pre><pre>let v = v.replace(&quot;^&quot;, &quot;&quot;);</pre><pre>let link = get_tarball_download_link_and_name(&amp;k, &amp;v).await;</pre><pre>match link {</pre><pre>Ok(link) =&gt; {</pre><pre>download_package(link).await.unwrap();</pre><pre>}</pre><pre>Err(err) =&gt; {</pre><pre>eprintln!(&quot;{}&quot;, err)</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>println!(&quot;downloading dependency {} ...&quot;, package);</pre><pre>let link = get_tarball_download_link_and_name(&amp;package, &amp;version).await;</pre><pre>match link {</pre><pre>Ok(link) =&gt; {</pre><pre>download_package(link).await.unwrap();</pre><pre>}</pre><pre>Err(err) =&gt; {</pre><pre>eprintln!(&quot;{}&quot;, err)</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>And voila you have your node js package manager working for you. 🤪🤘🏻</p><p>I thought of adding things like post-install, preinstall scripts processing, etc but I left that for another day.</p><p><strong>Conclusion</strong>:</p><p>Building a robust package manager like yarn or npm is no easy task but can be very fun and challenging. Though we still have a couple of things to implement like caching, <strong>bonnie.lock.toml</strong> file, etc. But this should work well as a POC. Thanks for reading</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e6b2389a634" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[0–100 in Angular: Part 6]]></title>
            <link>https://medium.com/vannila/0-100-in-angular-part-6-30240d9f2a1a?source=rss-c4e6bc2d8b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/30240d9f2a1a</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[resolver]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Valentine Oragbakosi]]></dc:creator>
            <pubDate>Fri, 01 Nov 2019 14:00:54 GMT</pubDate>
            <atom:updated>2019-11-01T14:00:54.647Z</atom:updated>
            <content:encoded><![CDATA[<p>In our last part of this series, we learned some beneficial things in Angular which include: Making Calls, feature modules, etc. See article <a href="https://medium.com/vannila/0-100-in-angular-part-5-4bc0a396a796">here</a>.</p><p>In today’s series, we would be diving into resolvers. If you recall vividly, you would remember that sometimes Angular routes faster than we can get data from our server thus giving us an error saying data is undefined. There is excellent news, Angular has a way to solve that problem and it uses resolvers.</p><p><strong>Resolvers</strong>: Resolvers are a way to suspend the component from loading until the necessary data is sent over to the client. It makes use of the Angular activated route.</p><p>Let’s see how it works</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r2fI4HJcCI0F0n9IGWdKYw.png" /></figure><p>Unfortunately, Angular doesn’t generate the resolver file for us, we would have to do that manually.</p><p>From our previous series code base, create a <strong><em>data.ressolvers.ts</em></strong> file the <strong><em>src/app/user</em></strong> directory and add the following piece of code there:</p><pre>import { Injectable } from &#39;@angular/core&#39;;</pre><pre>import { empty} from &#39;rxjs&#39;</pre><pre>import { Resolve } from &#39;@angular/router&#39;;</pre><pre>import { catchError } from &#39;rxjs/operators&#39;;</pre><pre>import { ActivatedRouteSnapshot } from &#39;@angular/router&#39;;</pre><pre>import {UserService} from &#39;./user.service&#39;<br></pre><pre>@Injectable()</pre><pre>export class GetUsers implements Resolve&lt;any&gt; {</pre><pre>constructor(private data:UserService) {}</pre><pre>resolve(){</pre><pre>return this.data.getUser().pipe(catchError((err)=&gt;{</pre><pre>return empty();</pre><pre>}))</pre><pre>}}</pre><p>This simply creates a new class GetUsers that implements Resolve. Notice we also import UserService and returned the value we get from it. If there is an error, it would not return any component. Next step, we have to tell our module that this resolver exists.</p><p>Import the resolver class in the module and add it to your providers.</p><pre>import {GetUsers} from &#39;./data.resolvers&#39;</pre><pre>providers: [GetUsers]</pre><p>Finally, we add it to our routing to make sure the conditions of the resolvers are met before routing takes place. Import it to your user routing file and modify the route where you get the list of users as such:</p><pre>import {GetUsers} from &#39;./data.resolvers&#39;</pre><pre>{</pre><pre>path:&#39;user&#39;,</pre><pre>component:UserComponent,</pre><pre>resolve:{userInfo:GetUsers}</pre><pre>}</pre><p>This would resolve the list of users in this route with the snapshot userInfo. Let’s now see how we retrieve this data in our component.</p><p>In our user component where we got the list of all the users, go ahead and add the following piece of code:</p><pre>import { ActivatedRoute } from &#39;@angular/router&#39;;</pre><pre>constructor(private router:ActivatedRoute) { }<br>list:any</pre><pre>ngOnInit() {</pre><pre>this.list=this.router.snapshot.data[&#39;userInfo&#39;]</pre><pre>}</pre><p>Notice here that we didn’t have to subscribe to our service on init, we just get the data from the activated route snapshot.</p><p>Let’s now implement resolvers for getting user by id.</p><p>As before go to your resolver file and add the following piece of code:</p><pre>@Injectable()</pre><pre>export class GetUserId implements Resolve&lt;any&gt; {</pre><pre>constructor(private data:UserService) {}</pre><pre>resolve(route: ActivatedRouteSnapshot){</pre><pre>return this.data.getProfile(route.paramMap.get(&#39;id&#39;)).pipe(catchError((err)=&gt;{</pre><pre>return empty();</pre><pre>}))</pre><pre>}</pre><pre>}</pre><p>Notice this is slightly different from the resolver class earlier because in this case, we have to use the id param from the route to make an API call. So we get the id using <strong>route.paramMap.get(‘id’)</strong> and pass it into the method.</p><p>Go ahead and update your module file and profile routing and profile component following the above example.</p><p>If all goes correctly, you would notice that you no longer the undefined error when you click the user profile.</p><p>And that’s how resolvers work in Angular folks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30240d9f2a1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vannila/0-100-in-angular-part-6-30240d9f2a1a">0–100 in Angular: Part 6</a> was originally published in <a href="https://medium.com/vannila">Vannila</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[0–100 in Angular: Part 5]]></title>
            <link>https://medium.com/vannila/0-100-in-angular-part-5-4bc0a396a796?source=rss-c4e6bc2d8b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bc0a396a796</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Valentine Oragbakosi]]></dc:creator>
            <pubDate>Tue, 22 Oct 2019 02:10:10 GMT</pubDate>
            <atom:updated>2019-10-22T02:10:10.700Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello guys, welcome to another series on Angular. In our last series we talked about routing extensively and route guard. You can read up <a href="https://medium.com/vannila/0-100-in-angular-part-4-c5c7e5688281">here</a>. In this part, we would talk about the following concepts:</p><ol><li>Feature module</li><li>Dependency Injection</li><li>Parent and children components</li><li>API calls (in Angular)</li><li>Services</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*ZOw0vt-VsIk96mm3-RvlYQ.jpeg" /></figure><p><strong>Feature module</strong> is a way of creating more modules other than the default one given to us by Angular. It helps keep our code organized and separate different parts of our application based on their concerns</p><p><strong>Dependency Injection</strong> is simply a technique in programming where an object supplies the dependencies to another object thus allowing code to be abstracted and reused.</p><p><strong>Parent and Children component</strong> is simple having a parent component with other sub-components that we call children component.</p><p><strong>API calls</strong>. In real life, we would have our angular application communicate with an API so as to get, post, delete, put, etc data. Angular uses HttpClient which is an inbuilt feature in Angular that allows us to make AJAX calls.</p><p><strong>Services</strong> in Angular is where we mostly keep code that would be reused across different components and classes. It helps with reusable code.</p><p>In this tutorial, we would be using JSON-server as our API. It is an npm package that allows us to set up a fake API in a couple of seconds. It’s a very good tool I use a lot. To install, run the command</p><pre>npm install -g json-server</pre><p>If you are using GNU/Linux, you might want to give it root access</p><pre>sudo npm install -g json-server</pre><p>Next up, create a db.json file anywhere you please and add the following piece of JSON there:</p><pre>{<br>  &quot;users&quot;: [<br>    { &quot;id&quot;: 1, &quot;name&quot;: &quot;Chidi Nwoke&quot;, &quot;email&quot;: &quot;<a href="/service/mailto:chidi@gmail.com">chidi@gmail.com</a>&quot; },<br>    { &quot;id&quot;: 2, &quot;name&quot;: &quot;Oge Okonkwo&quot;, &quot;email&quot;: &quot;<a href="/service/mailto:oge@gmail.com">oge@gmail.com</a>&quot; },<br>    { &quot;id&quot;: 3, &quot;name&quot;: &quot;David Tayo&quot;, &quot;email&quot;: &quot;<a href="/service/mailto:tayomil@gmail.com">tayomil@gmail.com</a>&quot; }<br>  ]<br>}</pre><p>After that, go to the directory you created the db.json file and run the command</p><pre>json-server --watch db.json</pre><p>This would start a server and if all goes well, you should see the list of users in your browser if you visit <a href="http://localhost:3000/users"><strong><em>http://localhost:3000/users</em></strong></a> and the first user if you visit <a href="http://localhost:3000/users"><strong><em>http://localhost:3000/users</em></strong></a><strong><em>/1.</em></strong></p><p>Now that we have everything set up, let’s get started with our Angular application. First, we want to create our new module which we would call “user”. To do that, run the command</p><pre>ng generate module user</pre><p>This would create a new folder called user with a <strong><em>user.module.ts</em></strong> file. Let’s go ahead and inform the original <strong><em>app.module.ts</em></strong> file about its existence. First, we import it into the <strong><em>app.module.ts, </em></strong>and add it to our imports as such:</p><pre>import {UserModule} from &#39;./user/user.module&#39;;</pre><pre>imports: [</pre><pre>UserModule</pre><pre>]</pre><p>Now we are good to go. Let’s go ahead and create some new components for our new module. We would create a home component, user (for listing all the users and adding new users) component, profile (for getting a single user) component, and edit component. Run the following command</p><pre>ng g c user/home</pre><pre>ng g c user/profile</pre><pre>ng g c user/user</pre><pre>ng g c user/edit</pre><p>Now that we have the following component, let’s go ahead and create routing for them. In the <strong><em>src/app/user</em></strong> folder create a <strong><em>user-routing.module.ts</em></strong> file. Add the following code there</p><pre>import { Routes, RouterModule } from &#39;@angular/router&#39;;</pre><pre>import { HomeComponent } from &#39;./home/home.component&#39;;</pre><pre>import { UserComponent } from &#39;./user/user.component&#39;;</pre><pre>import { ProfileComponent } from &#39;./profile/profile.component&#39;;</pre><pre>import { EditComponent } from &#39;./edit/edit.component&#39;</pre><pre>const UserRoutes: Routes = [</pre><pre>{ path: &#39;user&#39;,</pre><pre>component:HomeComponent,</pre><pre>children: [</pre><pre>{</pre><pre>path:&#39;user&#39;,</pre><pre>component:UserComponent</pre><pre>},</pre><pre>{</pre><pre>path:&#39;profile/:id&#39;,</pre><pre>component:ProfileComponent</pre><pre>},</pre><pre>{</pre><pre>path:&#39;edit/:id&#39;,</pre><pre>component:EditComponent</pre><pre>}</pre><pre>]</pre><pre>}</pre><pre>];</pre><pre>export const UserRouter = RouterModule.forChild(UserRoutes);</pre><p>Now let’s inform our <strong><em>user.module.ts</em></strong> file of this new route we created. To do that, we import the user router class as such:</p><pre>import {UserRouter} from &#39;./user-routing.module&#39;;</pre><pre>imports: [</pre><pre>UserRouter</pre><pre>]</pre><p>To make everything work, Let’s add our router outlet in our parent component which in this case is the home component. Open the HTML of the home component and add the following piece of code for the header and router outlet</p><pre>&lt;style&gt;</pre><pre>:host {</pre><pre>font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, Roboto, Helvetica, Arial, sans-serif, &quot;Apple Color Emoji&quot;, &quot;Segoe UI Emoji&quot;, &quot;Segoe UI Symbol&quot;;</pre><pre>font-size: 14px;</pre><pre>color: #333;</pre><pre>box-sizing: border-box;</pre><pre>-webkit-font-smoothing: antialiased;</pre><pre>-moz-osx-font-smoothing: grayscale;</pre><pre>}</pre><pre>.spacer {</pre><pre>flex: 1;</pre><pre>}</pre><pre>.toolbar {</pre><pre>height: 60px;</pre><pre>margin: -8px;</pre><pre>display: flex;</pre><pre>align-items: center;</pre><pre>background-color: #1976d2;</pre><pre>color: white;</pre><pre>font-weight: 600;</pre><pre>}</pre><pre>.toolbar img {</pre><pre>margin: 0 16px;</pre><pre>}</pre><pre>.toolbar #twitter-logo {</pre><pre>height: 40px;</pre><pre>margin: 0 16px;</pre><pre>}</pre><pre>.toolbar #twitter-logo:hover {</pre><pre>opacity: 0.8;</pre><pre>}</pre><pre>.class2{</pre><pre>color:black;</pre><pre>}</pre><pre>@media screen and (max-width: 575px) {</pre><pre>svg#rocket-smoke {</pre><pre>display: none;</pre><pre>visibility: hidden;</pre><pre>}</pre><pre>}</pre><pre>&lt;/style&gt;</pre><pre>&lt;!-- Toolbar --&gt;</pre><pre>&lt;div class=&quot;toolbar&quot; role=&quot;banner&quot;&gt;</pre><pre>&lt;img</pre><pre>width=&quot;40&quot;</pre><pre>alt=&quot;Angular Logo&quot;</pre><pre>src=&quot;data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==&quot;</pre><pre>/&gt;</pre><pre>&lt;span&gt;Welcome&lt;/span&gt;</pre><pre>&lt;div class=&quot;spacer&quot;&gt;&lt;/div&gt;</pre><pre>&lt;a aria-label=&quot;Angular on twitter&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot; href=&quot;https://twitter.com/angular&quot; title=&quot;Twitter&quot;&gt;</pre><pre>&lt;svg id=&quot;twitter-logo&quot; height=&quot;24&quot; data-name=&quot;Logo — FIXED&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; viewBox=&quot;0 0 400 400&quot;&gt;</pre><pre>&lt;defs&gt;</pre><pre>&lt;style&gt;</pre><pre>.cls-1 {</pre><pre>fill: none;</pre><pre>}</pre><pre>.cls-2 {</pre><pre>fill: #ffffff;</pre><pre>}</pre><pre>&lt;/style&gt;</pre><pre>&lt;/defs&gt;</pre><pre>&lt;rect class=&quot;cls-1&quot; width=&quot;400&quot; height=&quot;400&quot; /&gt;</pre><pre>&lt;path class=&quot;cls-2&quot; d=&quot;M153.62,301.59c94.34,0,145.94-78.16,145.94-145.94,0-2.22,0-4.43-.15-6.63A104.36,104.36,0,0,0,325,122.47a102.38,102.38,0,0,1-29.46,8.07,51.47,51.47,0,0,0,22.55-28.37,102.79,102.79,0,0,1-32.57,12.45,51.34,51.34,0,0,0-87.41,46.78A145.62,145.62,0,0,1,92.4,107.81a51.33,51.33,0,0,0,15.88,68.47A50.91,50.91,0,0,1,85,169.86c0,.21,0,.43,0,.65a51.31,51.31,0,0,0,41.15,50.28,51.21,51.21,0,0,1-23.16.88,51.35,51.35,0,0,0,47.92,35.62,102.92,102.92,0,0,1-63.7,22A104.41,104.41,0,0,1,75,278.55a145.21,145.21,0,0,0,78.62,23&quot;</pre><pre>/&gt;</pre><pre>&lt;/svg&gt;</pre><pre>&lt;/a&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;div class=&quot;content&quot; role=&quot;main&quot;&gt;</pre><pre>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><p>The <strong>router-outlet</strong> is where the child component would be rendered when a new child route is hit. Now hit <strong><em>localhost: 4200/user, localhost:4200/user/user, localhost:4200/user/profile/1 </em></strong>and see how our children parent component relates.</p><p>Let’s generate a new user service so as to communicate with our fake API. Run the command</p><pre>ng g service user/user</pre><p>Now that our service is generated, let’s go ahead and import HTTP client module into our user module as such:</p><pre>import { HttpClientModule } from &#39;@angular/common/http&#39;;</pre><pre>import:[</pre><pre>HttpClientModule<br>]</pre><p>The next step is to import HttpClient into our <strong><em>user.service.ts</em></strong> file and add it to our constructor as such</p><pre>import { HttpClient } from &#39;@angular/common/http&#39;;</pre><pre>constructor(private http:HttpClient) { }</pre><p>Having done that, let’s create all the methods we would need which include: getting all users, get user by id, edit user, add user, and delete a user. Thankfully JSON-server has all these features</p><p>The method to get all users:</p><pre>getUser(){</pre><pre>return this.http.get(&#39;http://localhost:3000/users&#39;)</pre><pre>}</pre><p>As you can see, the HttpClient makes a get request to our endpoint and returns the value it gets from it.</p><p>To get user by id:</p><pre>getProfile(id){</pre><pre>return this.http.get(&#39;http://localhost:3000/users/&#39;+id)</pre><pre>}</pre><p>This takes in a parameter that is the id of the user and appends it to the endpoint to get the user details.</p><p>To add a new user:</p><pre>addUser(data){</pre><pre>return this.http.post(&#39;http://localhost:3000/users&#39;, data)</pre><pre>}</pre><p>We pass in a parameter called data to this function. This data is the value of the form we want to add</p><p>To edit user:</p><pre>editUser(data, id){</pre><pre>return this.http.put(&#39;http://localhost:3000/users/&#39;+id, data)</pre><pre>}</pre><p>This method takes in two parameters which are the data we want to update and the id of the user we want to update their details.</p><p>To delete user:</p><pre>deleteUser(id){</pre><pre>return this.http.delete(&#39;http://localhost:3000/users/&#39;+id)</pre><pre>}</pre><p>This method takes in the id of the user we want to delete. Now let’s make these methods work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*S-m_Vglp09l2sa1aO9bDDA.jpeg" /></figure><p>Let’s first of us import the user service into our <strong><em>src/app/user/user/user.component.ts</em></strong> file and use the get user method. This is a clear example of dependency injection in action</p><pre>import {UserService} from &#39;../user.service&#39;</pre><pre>//add it to your constructor</pre><pre>list:any</pre><pre>ngOnInit() {</pre><pre>this.data.getUser().subscribe(value=&gt;{</pre><pre>this.list=value</pre><pre>})</pre><pre>}</pre><p>We added the code on the initialization of the component because we want to get the list once the component is initialized. The data.getUser() is what references the getUser() method in our service. After doing that, we have to subscribe to the method and take the value returned by the method. Imagine subscribe in this cast like promises. To view the list in our HTML, add the following piece of code to the HTML file</p><pre>&lt;ul *ngFor=&quot;let a of list&quot;&gt;</pre><pre>&lt;li &gt;{{a.name}}&lt;/li&gt;</pre><pre>&lt;li&gt;{{a.email}}&lt;/li&gt;</pre><pre>&lt;/ul&gt;</pre><p>Voila, our code works :) let&#39;s move on.</p><p>Now we would add a link that links to a user profile. Let’s modify our HTML to accommodate this</p><pre>&lt;ul *ngFor=&quot;let a of list&quot;&gt;</pre><pre>&lt;li &gt;{{a.name}}&lt;/li&gt;</pre><pre>&lt;li&gt;{{a.email}}&lt;/li&gt;</pre><pre>&lt;a routerLink=&quot;/user/profile/{{a.id}}&quot;&gt;profile&lt;/a&gt;</pre><pre>&lt;/ul&gt;</pre><p>Now let’s add the user data from our API to our profile page. Import the user service as described above and add it to your constructor. In this new component, we would also need to import activated Route to get the parameter from the current route so as to make a query with it (recall that our profile component has a /: id as an identifier for unique users).</p><p>Your profile component should have a constructor that looks like this:</p><pre>parameter:string</pre><pre>constructor(private data:UserService, private router:ActivatedRoute) {</pre><pre>this.router.params.subscribe(params =&gt; this.parameter = params.id)</pre><pre>}</pre><p>The router.params.subscribe is what get’s the value of the current param, whether 1, 2 or 3. Add the following on init:</p><pre>this.data.getProfile(this.parameter).subscribe(value=&gt;{</pre><pre>this.user=value</pre><pre>})</pre><pre>}</pre><p>In your profile view, we can now go ahead and add the following to view the details:</p><pre>&lt;h3&gt;</pre><pre>{{user.name}}</pre><pre>&lt;/h3&gt;</pre><pre>&lt;p&gt;{{user.email}}&lt;/p&gt;</pre><p>Let’s go back to our user component and add a form field to add new users. Import the form module and reactive form module to your user module and of course, add them to the imports.</p><p>Set up your form as we covered <a href="https://medium.com/vannila/0-100-in-angular-part-2-c2ac5cde9364">this</a> series.</p><p>Your submit method should look like this</p><pre>submit(){</pre><pre>var userValue=this.newUser.value;</pre><pre>this.data.addUser(userValue).subscribe(value=&gt;{</pre><pre>this.list.push(value);</pre><pre>})</pre><pre>}</pre><p>So that on successful submission, the list.push() method appends the item to our list without reloading the page.</p><p>Your form should also look like</p><pre>&lt;form [formGroup]=&quot;newUser&quot; (ngSubmit)=&quot;submit()&quot;&gt;</pre><pre>&lt;input placeholder=&quot;name&quot; type=&quot;text&quot; formControlName=&quot;name&quot;&gt;</pre><pre>&lt;input placeholder=&quot;email&quot; type=&quot;email&quot; formControlName=&quot;email&quot;&gt;</pre><pre>&lt;button [disabled]=&quot;newUser.invalid&quot;&gt;submit&lt;/button&gt;</pre><pre>&lt;/form&gt;</pre><p>So if yours work well, whenever you add a new name, it appends to your db.json file. Greate right? Now let’s make it possible to delete names from the list. Let’s modify our list in the user component HTML file once again to this.</p><pre>&lt;ul *ngFor=&quot;let a of list&quot;&gt;</pre><pre>&lt;li &gt;{{a.name}}&lt;/li&gt;</pre><pre>&lt;li&gt;{{a.email}}&lt;/li&gt;</pre><pre>&lt;a routerLink=&quot;/user/profile/{{a.id}}&quot;&gt;profile&lt;/a&gt;</pre><pre>&lt;button (click)=&quot;delete(a)&quot;&gt;delete&lt;/button&gt;</pre><pre>&lt;/ul&gt;</pre><p>Of course, be sure to create a delete method in your TS file that takes in one parameter. The delete method should look like this:</p><pre>delete(user){</pre><pre>this.data.deleteUser(user.id).subscribe(value=&gt;{</pre><pre>var index=this.list.indexOf(user);</pre><pre>this.list.splice(index, 1);</pre><pre>})</pre><pre>}</pre><p>This splice the object we delete clicked after the delete method is successful.</p><p>That was a whole lot to take in at once, right? Try pushing yourself and writing the edit method all by yourself.</p><p>Before I leave, you might have noticed an error on your web console that tells you that name and email is undefined but it, later on, goes to display. The reason is simply becauseAngular router is very fast, so it routes before the API call is complete. In a future series, we would solve this problem by adding resolvers to resolve the API call before the component is loaded.</p><p>Till then, have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bc0a396a796" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vannila/0-100-in-angular-part-5-4bc0a396a796">0–100 in Angular: Part 5</a> was originally published in <a href="https://medium.com/vannila">Vannila</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[0–100 in Angular: Part 4]]></title>
            <link>https://medium.com/vannila/0-100-in-angular-part-4-c5c7e5688281?source=rss-c4e6bc2d8b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5c7e5688281</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Valentine Oragbakosi]]></dc:creator>
            <pubDate>Sun, 06 Oct 2019 12:53:50 GMT</pubDate>
            <atom:updated>2019-10-06T12:53:50.498Z</atom:updated>
            <content:encoded><![CDATA[<p>Good day guys, in the last part of this series we dived into routing and pipes. Read more <a href="https://medium.com/vannila/0-100-in-angular-part-3-7668009516e3">here</a>. Today we would go a step further and learn the following concepts:</p><ol><li><strong>Routing with parameters</strong></li><li><strong>Redirecting</strong></li><li><strong>Route guard</strong></li></ol><p>So let’s get started here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*xWuiV_8GPfIgZd1rRrkAkQ.jpeg" /></figure><p>Routing with parameters is a concept used a lot in programming to route to a page or endpoint to get data for a particular item or group of items using a unique identifier. eg to get the profile for user 1 might require us to visit the page <a href="https://myweb.com/user/1"><strong><em>https://myweb.com/user/1</em></strong></a><strong><em> </em></strong>this would route us to the user 1 page and get his data. Notice the 1 at the end of the route, it’s the unique identifier for user 1. It can also be changed to another number to get that user identifier, meaning that it’s shouldn’t be hardcoded.</p><p>Redirecting is a very familiar concept that we all have experienced. For example, on a successful login/signup, you should be taken to another page.</p><p>Route guard is a way to protect certain routes from unauthorized users. For example, users who are not logged in should not be allowed to a particular page. So we achieve that using route guard.</p><p>Let’s start with routing with parameters:</p><p>Generate a new route called item (or anything you wish) with the command</p><pre>ng g c item</pre><p>As we specified in an earlier series, specify the route for the item component in the <strong><em>src/app/app-routing.module.ts</em></strong> as such</p><pre>{</pre><pre>path:&#39;item/:id&#39;,</pre><pre>component: ItemComponent</pre><pre>}</pre><p>You would notice that unlike the other routes, this has a ‘<strong><em>/: id</em></strong>’ in it. That <strong>id</strong> is the parameter that we pass into the URL when accessing the route, so if we navigate to the route <a href="http://localhost:4200/item/23"><strong>http://localhost:4200/item/2</strong></a> we would see item component. In this case, 2 is our parameter. Great!!!</p><p>Now, how do we get ou parameter to be used in our application? The first step is easy.</p><p>Import activated route into your item component and specify it in your constructor as such</p><pre>import { ActivatedRoute } from &#39;@angular/router&#39;;</pre><pre>//code here</pre><pre>constructor(private router:ActivatedRoute) { }</pre><p>This module would allow us to get the current route and work with it. Next, we specify a variable of type string with the name parameter and assign it to the current parameter inside our constructor as such:</p><pre>parameter:string</pre><pre>constructor(private router:ActivatedRoute) {</pre><pre>this.router.params.subscribe(params =&gt; this.parameter = params.id)</pre><pre>}</pre><p>This would subscribe to the current parameter (we would learn subscribe extensively in a later series) and assign the value of the promise to our parameters variable we created.</p><p>You can now view the current parameter in the view by adding this to our item HTML file:</p><pre>&lt;P&gt;{{parameter}}&lt;/p&gt;</pre><p>Whenever we change our parameter, we would see the value in the view. In a later series, we would see how more useful this can be.</p><h3>Redirecting</h3><p>To understand redirecting, let’s create a login component that would save a token comprised of the user name and password and save it in local storage on successful login, after that, redirect the user to the login page.</p><p>Type the command</p><pre>ng g c login</pre><p>In your terminal, specify the route for the login page as we did earlier, now navigate to your login component and create a reactive form. If you are unfamiliar with reactive forms, reference to our previous series on it <a href="https://medium.com/vannila/0-100-in-angular-part-2-c2ac5cde9364">here</a>.</p><p>The form should fields of name and password. The password field should accept a minimum of 6 characters. Your form group should look like this:</p><pre>this.LoginForm=this.fb.group({</pre><pre>name:[&#39;&#39;, Validators.required],</pre><pre>password:[&#39;&#39;, [Validators.minLength(6), Validators.required]]</pre><pre>})</pre><p>Next in your login component, import Router as such:</p><pre>import {Router} from &#39;@angular/router&#39;</pre><p>Don’t forget to define it in your constructor. This component would be used for our redirecting feature.</p><p>Create the view for the form as such:</p><pre>&lt;form (ngSubmit)=&quot;submit()&quot; [formGroup]=&quot;LoginForm&quot;&gt;</pre><pre>&lt;input type=&quot;text&quot; formControlName=&quot;name&quot; placeholder=&quot;name&quot;&gt;</pre><pre>&lt;input type=&quot;password&quot; formControlName=&quot;password&quot; placeholder=&quot;password&quot;&gt;</pre><pre>&lt;button [disabled]=&quot;LoginForm.invalid&quot;&gt;submit&lt;/button&gt;</pre><pre>&lt;/form&gt;</pre><p>Our submit function should look like this:</p><pre>submit(){</pre><pre>var formValue=this.LoginForm.value;</pre><pre>localStorage.setItem(&#39;token&#39;, formValue)</pre><pre>this.router.navigate([&#39;&#39;])</pre><pre>}</pre><p>This piece of code just simply states that first, get the value of the login form, save it in local storage with the name token, then navigate to our landing page which we specified in our routing page in a previous series.</p><p><strong>Note</strong>: In a real-life application, we want to communicate with a real server to validate the user credentials. So if you open the local storage of your browser, you would see something saved there with the name token. Great right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*fRb8IxCFmvi-37zHhogpcw.jpeg" /></figure><h3>Route Guard</h3><p>Angular has inbuilt features for guarding route. So now, let’s make it impossible for a user to visit the item page without having logged in.</p><p>Type in the command in your terminal to generate an auth guard with the name <strong>auth</strong></p><pre>ng g guard auth</pre><p>If you are using the latest version of angular CLI, you would be prompted on what interface you want to implement. Go ahead and choose <strong>CanActivate. </strong>Next, we generate a service (service would also be explained in details in the future series) with the name <strong>tutorial</strong> with the command in your terminal</p><pre>ng g service tutorial</pre><p>Add the following piece of code in the <strong><em>src/app/tutorial.service.ts</em></strong> file:</p><pre>loggedIn(){</pre><pre>return !!localStorage.getItem(&#39;token&#39;)</pre><pre>}</pre><p>This would return true or false if the token is found in local storage</p><p>next in the <strong><em>auth.guard.ts</em></strong> file, clear everything there and add this piece of code</p><pre>import { Injectable } from &#39;@angular/core&#39;;</pre><pre>import { CanActivate} from &#39;@angular/router&#39;;</pre><pre>import { Router } from &#39;@angular/router&#39;;</pre><pre>import { TutorialService} from &#39;./tutorial.service&#39;;</pre><pre>@Injectable({</pre><pre>providedIn: &#39;root&#39;</pre><pre>})</pre><pre>export class AuthGuard implements CanActivate {</pre><pre>constructor(private data:TutorialService, private router:Router){}</pre><pre>canActivate():boolean{</pre><pre>if(this.data.loggedIn()){</pre><pre>return true</pre><pre>}else{</pre><pre>this.router.navigate([&#39;login&#39;])</pre><pre>return false</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>This tells the app to route to the login page if the loggedin function in the service returns false. Now, let’s make it work. First, import it into your <strong><em>app.module.ts </em></strong>and add it to your providers</p><pre>import {AuthGuard} from &#39;./auth.guard&#39;</pre><pre>providers: [AuthGuard]</pre><p>Next, import it into your app-routing.module.ts file the way we imported it to our app module file and update your item routing to look like this:</p><pre>{</pre><pre>path:&#39;item/:id&#39;,</pre><pre>component: ItemComponent,</pre><pre>canActivate:[AuthGuard]</pre><pre>}</pre><p>This would specify the rules we declared in our auth guard for the item component. So if we go-ahead to the local storage and clear the token, we would be unable to access the item page, we would be redirected to the login page.</p><p>Thanks for reading, see you later.</p><h3>BYE!!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5c7e5688281" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vannila/0-100-in-angular-part-4-c5c7e5688281">0–100 in Angular: Part 4</a> was originally published in <a href="https://medium.com/vannila">Vannila</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[0–100 in Angular: Part 3]]></title>
            <link>https://medium.com/vannila/0-100-in-angular-part-3-7668009516e3?source=rss-c4e6bc2d8b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7668009516e3</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Valentine Oragbakosi]]></dc:creator>
            <pubDate>Tue, 01 Oct 2019 11:36:10 GMT</pubDate>
            <atom:updated>2019-10-01T11:36:10.648Z</atom:updated>
            <content:encoded><![CDATA[<p>In our last part of the series, we talked about Angular life cycle hook, reactive forms, single data binding, etc. You can check that all <a href="https://medium.com/vannila/0-100-in-angular-part-2-c2ac5cde9364">here</a>. In this part, we would be learning other concepts in Angular that make building Single Page Applications (SPA) easier.</p><p>Concepts we would learn include:</p><ol><li>Routing</li><li>Reusable components</li><li>Pipes</li><li>Custome pipes</li></ol><p>Let’s take a minute to explain these terms and what they mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*gvPAXMA_Yt1d_hFzulB0ag.jpeg" /></figure><p><strong>Routing</strong>: Routing is simply a way of rendering new components when a user clicks of a link or manually visit the link that leads to a component. The logic of this is done in the <strong><em>src/app/app-routing.module.ts. </em></strong>Angular makes this super easy to set up, and we would see how in a jiffy.</p><p><strong>Reusable components</strong>: This is another feature of Angular that makes it super cool to use. We can reuse components in another component, thus not needing to repeat ourselves. For example, you can have a header component and want to use it among so many other components. Instead of rewriting the headers every single time, we just use the header selector. We would also see how to use this.</p><p><strong>Pipes</strong>: This is how we format text, numbers, dates, etc .using some inbuilt rules in Angular.</p><p><strong>Custom pipes</strong>: This is a way of designing your pipes and giving it a set of rules that you decide. Talk about being your boss.</p><p>Let the coding begin!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*SIGTMCjJvR5TQZxpA1PmTA.png" /></figure><p>To get started, let’s generate 2 new components in addition to our home component. We would call it header component and about component. So in your terminal, run the following command</p><pre>ng g c header</pre><p>To generate the header component, and</p><pre>ng g c about</pre><p>To generate the about component.</p><p>Next, we import them into our <strong><em>app-routing.module.ts</em></strong> file so that we could use them for our routing as such:</p><pre>import { HeaderComponent } from &#39;./header/header.component&#39;;</pre><pre>import { AboutComponent } from &#39;./about/about.component&#39;;</pre><p>This simple line would make these components accessible to our routing. Now let’s create the route URL for these different components.</p><p>Remember where we specified our home component to be the base route, add the following piece of code to that array of objects</p><pre>{</pre><pre>path:&#39;header&#39;,</pre><pre>component:HeaderComponent</pre><pre>},</pre><pre>{</pre><pre>path:&#39;about&#39;,</pre><pre>component:AboutComponent</pre><pre>}</pre><p>If all works out well, we should see the message ‘header works!’ when we visit <strong><em>localhost:4200/header</em></strong> and ‘about works!’ when we visit <strong><em>localhost:4200/about</em></strong>. But we don’t expect the user to manually change these routes from the browser when he visits our site, do we? So let’s add links so the header and make the header link accessible to our home component and about component.</p><p>To add links in angular, we don’t use the conventional <strong>href </strong>unless we are linking to an external site. To link to a different component, we use <strong>routerLink</strong> instead.</p><p>In your <strong><em>header.component.html</em></strong> file add the following piece of code</p><pre>&lt;ul style=&quot;text-decoration: none&quot;&gt;</pre><pre>&lt;li&gt;&lt;a routerLink=&quot;&quot;&gt;home&lt;/a&gt;&lt;/li&gt;</pre><pre>&lt;li&gt;&lt;a routerLink=&quot;/about&quot;&gt;about&lt;/a&gt;&lt;/li&gt;</pre><pre>&lt;/ul&gt;</pre><p>The <strong>routerLink</strong> we specified would create a link to the component as specified in the <strong><em>app-routing.module.ts</em></strong> file.</p><p>Let’s now make sure that this header file is accessible in our <strong><em>home.component.html</em></strong> file and our <strong><em>about.component.html</em></strong> files. To do this is relatively simple. Just go to your <strong><em>header.component.ts</em></strong> file and you would see a selector that has the name <strong>app-header</strong>. Copy it and input it into an HTML tag, then add it to your <strong><em>home.component.html </em></strong>and <strong><em>about.component.html </em></strong>files as such:</p><pre>&lt;app-header&gt;&lt;/app-header&gt;</pre><p>We have successfully added routing and reused the header component. Now let’s see how pipes work</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*vLMktSUXu_uzJcp6QXmLRQ.jpeg" /></figure><h4>PIPES</h4><p>Let’s say in your typescript, we have a string called name that says “angular is good” and we want to display this text in our HTML as lower case, upper case, or truncate it, pipes makes this super easy as such</p><pre>&lt;h3&gt;{{name| uppercase}}&lt;/h3&gt;</pre><pre>&lt;h3&gt;{{name| lowercase}}&lt;/h3&gt;</pre><pre>&lt;h3&gt;{{name| slice:0:6}}&lt;/h3&gt;</pre><p>The first one turns the string to a lower case, the second makes it upper case, while the third splice the string from the first to the sixth index. Pretty sweet right? It also works with currency, numbers, dates, arrays, etc. Let’s another example of formating date</p><p>Say we have the current date-time in your TS file, we can use pipe to show the current date or just the time, we can use pipe to format this date as such:</p><pre>&lt;h3&gt;{{today| date:&#39;d/M/y&#39;}}&lt;/h3&gt;</pre><pre>&lt;h3&gt;{{today| date:&#39;shortTime&#39;}}&lt;/h3&gt;</pre><pre>&lt;h3&gt;{{today|date:&#39;longTime&#39;}}&lt;/h3&gt;</pre><p>Our output should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*7HLD9ykCmekT4-trZjns3Q.png" /></figure><p>You can read more about the Angular pipe <a href="https://angular.io/guide/pipes">here</a>.</p><p>Now let’s create a custom pipe to get the square of numbers.</p><p>Create a file called <strong><em>sqr.pipe.ts</em></strong> in <strong><em>src/app</em></strong> directory add the following piece of code there</p><pre>import { Pipe, PipeTransform } from &#39;@angular/core&#39;;</pre><pre>@Pipe({name: &#39;sqrNumber&#39;})</pre><pre>export class sqrNumber implements PipeTransform{</pre><pre>transform(value: number): number {</pre><pre>return Math.pow(value, 2)</pre><pre>}</pre><pre>}</pre><p>We first have to import the pipe and PipeTransform from angular core, next we give the pipe a name that we would use when calling it. Then we define a set of rules and what our pipe should return, in this case, the square of the number.</p><p>After creating the pipe, we import it into our <strong><em>app.module.ts</em></strong> file and add it to our declarations, so that Angular would be aware it exists.</p><pre>//coe here<br>import {sqrNumber} from &#39;./sqr.pipe&#39;</pre><pre>@NgModule({</pre><pre>declarations: [</pre><pre>sqrNumber,</pre><pre>]</pre><p>Now we are free to use our pipe as we which. Create a variable in your typescript of type number and assign it a value. Then in your HTML, use the custom pipe like this</p><pre>&lt;h3&gt;the square of {{mynum}} is {{mynum|sqrNumber}}&lt;/h3&gt;</pre><p>This would produce this result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*BzAh4j-YacwfvR8DDY-GIw.png" /></figure><p>Great!!!</p><p>We now have a good grasp of more concepts in Angular. Next time, we take a deeper dive. Have a great day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7668009516e3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vannila/0-100-in-angular-part-3-7668009516e3">0–100 in Angular: Part 3</a> was originally published in <a href="https://medium.com/vannila">Vannila</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[0–100 in Angular: Part 2]]></title>
            <link>https://medium.com/vannila/0-100-in-angular-part-2-c2ac5cde9364?source=rss-c4e6bc2d8b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2ac5cde9364</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Valentine Oragbakosi]]></dc:creator>
            <pubDate>Sun, 29 Sep 2019 12:56:02 GMT</pubDate>
            <atom:updated>2019-09-29T12:56:02.537Z</atom:updated>
            <content:encoded><![CDATA[<p>In the first part of the series, we talked about setting up our angular environment and running it on a desirable port. In case you missed that, you can read more <a href="https://medium.com/vannila/0-100-in-angular-part-1-f2fab91ad5d6">here</a>. In this part, we would be building a simple list of staffs in a company and they email. We would use this simple application to learn the following</p><ol><li>Single data binding</li><li>Form submit</li><li>Data types</li><li>Angular common modules</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NiiP5FKUB317EmByGIBfaQ.jpeg" /><figcaption>let’s get started</figcaption></figure><p>First, let me define the following terms listed above</p><p><strong>Single Data Binding</strong>: In simple terms, this is a way to pass variables from your typescript component to your HTML component and updating the HTML DOM whenever the variable in your typescript changes.</p><p><strong>Form Submit: </strong>This is a way of taking input from the user and submitting it to a central pool (in our case we would use an array).</p><p><strong>Data Types</strong>: This is defining the data type our variable would accept eg string, Array&lt;number&gt;, object, any, etc.</p><p><strong>Angular Common modules: </strong>This is a module that contains the *ngFor, *ngIf, and *ngSwitch directive. The name of the directives are quite self-explanatory. The *ngFor is used to iterate over a collection of items, *ngIf accepts a true or false data type and shows the DOM if true but hides it if false, while *ngSwitch uses the switch case we are familiar with.</p><p>Now let’s code</p><p>Now open your <strong><em>src/app/app.component.html </em></strong>clear everything inside except</p><pre>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><p>This router outlet is important for our routing in the future so we want to keep it.</p><p>We would also want to create a new component and make it our landing page. Angular makes that very simple for us. Just open a terminal in your project directory and type the command</p><pre>ng g c home</pre><p>This would generate a home component in your <strong><em>src/app</em></strong> folder and add it as a declaration to your <strong><em>app.module.ts</em></strong> this would let the module know that you have a new component. If you open the home folder, you would see a couple of files created. The <strong><em>home.component.css</em></strong> file is where all our CSS for the home component goes, the <strong><em>home.component.html </em></strong>contains our home component Html, the <strong><em>home.component.spec.ts </em></strong>is for testing our home component while the <strong><em>home.component.ts</em></strong> is the typescript for our home component where all our logic goes.</p><p>Now let’s make it our landing page. The first thing to do is to import the home component into your <strong><em>src/app/app-routing.module.ts </em></strong>and add it as the base path like so</p><pre>import { HomeComponent } from &#39;./home/home.component&#39;;</pre><pre>const routes: Routes = [</pre><pre>{<br>path:&#39;&#39;,<br>component:HomeComponent</pre><pre>}</pre><pre>];</pre><p>This would tell Angular that we want to load this component when we are in the base URL of our application. If all works well, you should see a message that says “home works!” on your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*-9sHpw3WE89r7ExajOqrZQ.jpeg" /></figure><p>Now let’s start writing our employee list, shall we?</p><p>Now open your home.component.ts and declare a variable that would hold our list. Since this variable would hold a list of objects, we say</p><pre>list:Array&lt;object&gt;</pre><p>So now, Typescript knows to allow only objects in this array. After doing that, we would see very popular <strong>ngOnInt. </strong>This is Angular <strong>life cycle hook </strong>and what it does is to execute the code inside its curly braces whenever the component loads. And of course, we want to see our list when the component loads. So we add our array of objects inside of it as thus</p><pre>ngOnInit() {</pre><pre>this.list=[</pre><pre>{</pre><pre>name:&quot;Chidi Emma&quot;,</pre><pre>email:&quot;chidi43@gmail.com&quot;</pre><pre>},</pre><pre>{</pre><pre>name:&quot;Micheal Nwosu&quot;,</pre><pre>email:&quot;mike4real@yahoo.com&quot;</pre><pre>},</pre><pre>{</pre><pre>name:&quot;Bisola Nkiru&quot;,</pre><pre>email:&quot;buka4short@yahoo.com&quot;</pre><pre>},</pre><pre>]</pre><pre>}</pre><p>If all goes correctly, your <strong><em>home.component.ts </em></strong>file should look like this</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;</pre><pre>@Component({</pre><pre>selector: &#39;app-home&#39;,</pre><pre>templateUrl: &#39;./home.component.html&#39;,</pre><pre>styleUrls: [&#39;./home.component.css&#39;]</pre><pre>})</pre><pre>export class HomeComponent implements OnInit {</pre><pre>list:Array&lt;object&gt;</pre><pre>constructor() { }</pre><pre>ngOnInit() {</pre><pre>this.list=[</pre><pre>{</pre><pre>name:&quot;Chidi Emma&quot;,</pre><pre>email:&quot;chidi43@gmail.com&quot;</pre><pre>},</pre><pre>{</pre><pre>name:&quot;Micheal Nwosu&quot;,</pre><pre>email:&quot;mike4real@yahoo.com&quot;</pre><pre>},</pre><pre>{</pre><pre>name:&quot;Bisola Nkiru&quot;,</pre><pre>email:&quot;buka4short@yahoo.com&quot;</pre><pre>},</pre><pre>]</pre><pre>}</pre><pre>}</pre><p>Now let’s use our *ngFor directive to make sure we see all the list in our browser. And the easy way to do that is writing the following in our <strong><em>home.component.html.</em></strong></p><pre>&lt;div&gt;</pre><pre>&lt;ul *ngFor=&quot;let i of list&quot;&gt;</pre><pre>&lt;li&gt;</pre><pre>Name:{{i.name}}</pre><pre>Email:{{i.email}}</pre><pre>&lt;/li&gt;</pre><pre>&lt;/ul&gt;</pre><pre>&lt;/div&gt;</pre><p>If all goes well, we should see a list of names and emails on our browser. and just like that, we have our first Angular application (let’s throw a party).</p><p>Now let’s add the option of adding new names to the list via a form. And in this case, we would use Angular reactive form.</p><p>The first step is to add the form module to our <strong><em>app.module.ts </em></strong>and add it to our imports as such</p><pre>//other code here<br>import { FormsModule, ReactiveFormsModule } from &#39;@angular/forms&#39;;</pre><pre>imports:[</pre><pre>//other items here</pre><pre>FormsModule,</pre><pre>ReactiveFormsModule</pre><pre>]</pre><p>This would let angular know that we want to use this form in our component. Now that we have that out of the way, let’s go ahead and use the form in our <strong><em>home.component.ts</em></strong></p><ol><li>import the following in your <strong><em>home.component.ts</em></strong></li></ol><pre>import { FormControl, Validators, FormGroup, FormBuilder} from &#39;@angular/forms&#39;;</pre><p>2. Add the form builder in your constructor as such</p><pre>constructor(private fb:FormBuilder){}</pre><p>This would prepare the form builder object to be used in our class.</p><p>3. Create a variable called myForm that would hold our form group just as we did for list, but this would have a data type of FormGroup</p><pre>myForm:FormGroup</pre><p>4. Create the form instance on initialization and add validation</p><pre>this.myForm=this.fb.group({</pre><pre>name:[&#39;&#39;, Validators.required],</pre><pre>email:[&#39;&#39;, [Validators.email, Validators.required]]</pre><pre>})</pre><p>The empty quote tells the form to be empty on initialization and the validation on name says that name is a required field, while that on email says that email is also a required field that should be a valid email. This should be added in <strong>ngOnInt</strong></p><p>5. Let’s create the function to call when we submit the form (this should be outside ngOnint)</p><pre>submit(){</pre><pre>var formValue=this.myForm.value;</pre><pre>this.list.push(formValue)</pre><pre>}</pre><p>This takes the value from the form and append it to our array</p><p>6. Let’s make our <strong><em>app.component.html </em></strong>aware of this form and submit function. Create a form as thus:</p><pre>&lt;form (ngSubmit)=&quot;submit()&quot; [formGroup]=&quot;myForm&quot;&gt;</pre><pre>&lt;input type=&quot;text&quot; formControlName=&quot;name&quot; placeholder=&quot;name&quot;&gt;</pre><pre>&lt;input type=&quot;email&quot; formControlName=&quot;email&quot; placeholder=&quot;email&quot;&gt;</pre><pre>&lt;button [disabled]=&quot;myForm.invalid&quot;&gt;submit&lt;/button&gt;</pre><pre>&lt;/form&gt;</pre><p>There seems to be a lot happening here so let me explain. The <strong>ngSubmit</strong> is what tells the form which function to call when it wants to submit, the <strong>formGroup</strong> is what binds the Html form to the myForm form group in our typescript, the <strong>formControlName</strong> binds the form input to the names and validation we gave it in our typescript, while the <strong>disabled</strong> disables the button till the validations are met</p><p>If all works well, we should add names to the list and it would update to the DOM automatically without reloading the page. That’s the power of one-way data binding.</p><p>Since we updated our array, the data would also reflect in our list.</p><p>Now we can have a good grasp on many very important concepts in Angular. In your free time, update the code and make it able to delete names from the list. You can ask questions in the comment.</p><p>See you later</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*exb5Y56Ldvbkl6rHEOkj3g.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2ac5cde9364" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vannila/0-100-in-angular-part-2-c2ac5cde9364">0–100 in Angular: Part 2</a> was originally published in <a href="https://medium.com/vannila">Vannila</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[0–100 in Angular: Part 1]]></title>
            <link>https://medium.com/vannila/0-100-in-angular-part-1-f2fab91ad5d6?source=rss-c4e6bc2d8b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2fab91ad5d6</guid>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Valentine Oragbakosi]]></dc:creator>
            <pubDate>Sat, 28 Sep 2019 09:02:09 GMT</pubDate>
            <atom:updated>2019-09-29T09:17:08.119Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, this is a series of Angular tutorials to get you off your feet in angular and skyrocket you to the next level. In this series, we would start from the very basic to advanced concepts in Angular making it as simple as possible to understand.</p><figure><img alt="angular image" src="https://cdn-images-1.medium.com/max/1024/1*GmMtKznzJ1dS8sSzxzR3ow.png" /></figure><p>For this tutorial, we need the following things:</p><ol><li><strong>Node js</strong>: you can install it from <a href="https://nodejs.org/en/">here</a>. Please make sure you install version 10.16 and above because that’s the minimum required version</li><li><strong>NPM</strong>: This usually comes together with node js. So if you have installed node correctly, you should have this also.</li><li><strong>Angular CLI</strong> To install this, we open our command line or terminal and run the command</li></ol><pre>npm install -g @angular/cli</pre><p>If you are using GNU/Linux, you might want to give it root access so type the command</p><pre>sudo npm install -g @angular/cli</pre><p>supply your password and just like that you are a professional Angular developer. Just kidding, we still have a milestone to cross.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*0EQMrNyHVHbJJ2SD1lhDkw.gif" /></figure><p>Now that we have Angular all set up, let’s get this party started.</p><p>To create a new project, we open our terminal in the environment we wish to create the project. I’ll call my project vannila and I’ll create it in my JavaScript folder. So I’ll navigate to the JavaScript directory, open my terminal there and run the command</p><pre>ng new vannila</pre><p>This would ask you bunch of questions like if you would want routing and style sheet format you want. Well, I’ll pick yes because I want my app to have routing capabilities (I’ll explain this later) and I’ll also select CSS (though you can select any stylesheet format you are comfortable with). Then press enter and watch angular create bunch of files for you in the vannila directory it just created, after that it would install all the necessary dependencies and start your server. But what are dependencies? well, dependencies are libraries that your application is dependent on and needs it to run smoothly. Angular has a bunch of those eg @angular/core, @angular/forms, etc.</p><p>In case for some reason you angular CLI failed during installation thus not starting your server, no need to panic. We just navigate into the directory with the command</p><pre>cd vannila</pre><p>then we manually install the dependencies with the command</p><pre>npm install</pre><p>This would install all the dependencies stated in you vannila/package.json file. After that’s complete, run the command</p><pre>ng serve -o</pre><p>This command is simply telling Angular to serve your application and the -o tells it to open in the default browser.</p><p>And by default, Angular starts on port 4200 but if you wish to specify a new port you can run</p><pre>ng serve -o --port=3000</pre><p>This would start it on port 3000. Now we have our Angular set up, let’s understand what the different files/folders are.</p><p>You should have a folder structure that looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*x9k8EOhz7U3ViMSAQ25vcQ.png" /></figure><p><strong>e2e</strong>: This is where our e2e test are kept for running test</p><p><strong>node_modules: </strong>This folder contains all our dependencies</p><p><strong>src</strong>: Here we have our assets folder for keeping assets like images, CSS, javascript, etc. We also have the app folder that has our app.routing file for our routing, app.component.css for our CSS, app.component.html for the Html, app.component.ts for out typescript app.component.spec.ts for testing and app.module which groups all our related components, pipes, services, etc. This would be explained in details later with more examples. Other things to note in the src folder is the index.html and the style.css. The index.html is the entry point for our application. So if we need to add bootstrap CDN to our app, we just need to put it in the index.html and it would reflect in every other part of the application. While the style.css is the general styling, though every component has there style, the style.css would also affect every component in the application. Eg if you want every p tag to have a colour of red in the app, just specify that in your style.css</p><p>We also have a bunch of files like .gitignore which ignores files or folders when pushing to git, angular.json for our angular configuration, tsconfig.json for our typescript configuration (since Angular uses typescript), package.json to keep track of our packages, to specify start script and do other cool stuff, Readme.md file for adding a readme with markdown.</p><p>Next up, we would start building cool stuff with our Angular project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2fab91ad5d6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vannila/0-100-in-angular-part-1-f2fab91ad5d6">0–100 in Angular: Part 1</a> was originally published in <a href="https://medium.com/vannila">Vannila</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MY DISCOVERY]]></title>
            <link>https://medium.com/@oragbakosi13400/my-discovery-e0474b067426?source=rss-c4e6bc2d8b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0474b067426</guid>
            <category><![CDATA[inspiration]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Valentine Oragbakosi]]></dc:creator>
            <pubDate>Tue, 17 Apr 2018 16:33:37 GMT</pubDate>
            <atom:updated>2018-04-17T16:34:30.868Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello guys. So this is my first article on Medium and it’s also the first time I’m publicly writing about my journey into tech.</p><p>Every journey has a beginning and this is the story of my discovery of tech. Three years ago, I didn’t think I would have anything to do with writing softwares or coding until a phone call changed all that.</p><p>So I’ve always been this typical science freak who was enthusiastic about science things and how computers work. But I never wanted to be involved in writing softwares though my brother has been talking about Java and writing it as far back as 2009. But what was that phone call that changed all this? and who called? Trust me, it wasn’t Bill Gates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*K_yZiLiFU1EL00sDPZvtUg.jpeg" /><figcaption>This is what my face probably looked like then.</figcaption></figure><p>So one night, a friend of mine had an initiative to create a start up company which would involve a very complex algorithm and he wanted me in (maybe because I’ve always been a good boy). Anyways, the reason didn’t really matter. But he made a suggestion that we should all learn how to code so that we could build the app ourselves. Wait a sec, is this guy high? I don’t want to write any damn application let’s just partner with some developers already. But I reluctantly decided to learn coding. So I buzzed my bro who was already into Java and told him I wanted to learn how to code. So my class with my brother began. He told me what header tags were and what they meant and immediately gave assessment test. <strong>WTF</strong>!!! you have been practically speaking Latin all night and you now want examples? So I told him not to worry his ass, I’ll learn it on my own. Oh!!! did I mention that at this time I was still using a small symbian Nokia phone plus I had no laptop?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*q4KhrxhDBnyEA59p8yNE9w.jpeg" /><figcaption>my phone back then</figcaption></figure><p>But I was lucky the phone could open pdf files so I got some books on HTML and I began to read. For the first few days, it still sounded like Greek to me and of course I couldn’t practice plus I was actually a student of Biochemistry with billions of reactions to memorize. So my first text editor was my pen and paper. So for the first year (2015–2016) all I learnt was HTML and CSS.</p><p>IT changed that a great deal. So while my friends were busy mixing chemicals and analyzing DNA, I was learning JavaScript from a pdf but at this point I had gotten a small android phone which could accept a text editor so I could now test my HTML, CSS and JavaScript on my mobile phone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bx3VegloKVakLKaaXG_sRQ.jpeg" /><figcaption>let the coding begin</figcaption></figure><p>Okay guys school resumes and brings with it it’s brain drain and I really didn’t do much again in my final year though I began to lay the foundation for my Startup and attend meetups. And yes I finally had a laptop hallelujah.</p><p>It was until late last year that my learning sky rocketed and coincidentally it was the same time I finished school.</p><p>In this short period of time, I’ve managed to learn a lot of amazing things and worked on lots of amazing projects and moved to being a fullstack software developer who also makes bots. And I forgot to mention I’m currently an intern in Genesys tech hub as a backend developer.</p><p>So this is my discovery of how I found the tech within me and unleashed it.</p><p>So that’s my not so amazing story. Thanks for reading</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uAqNe8--HYX186fRvnoFpg.png" /><figcaption>bye for now.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0474b067426" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>