{"componentChunkName":"component---src-templates-post-template-js","path":"/posts/angular-get-the-ip-address-of-the-user","result":{"data":{"markdownRemark":{"id":"0519878d-1223-5e59-a4c4-48adef1bfdb3","html":"<p>In this short blog post, I will show you how to get the ip address of the user.</p>\n<blockquote>_I'm using v5 for this tutorial. If you are using v2/v4, just replace the HttpClient with just Http._</blockquote>\n<p>Here it goes:</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">import { Component } from &#39;@angular/core&#39;;\nimport {HttpClient} from &#39;@angular/common/http&#39;;\n@Component({\n  selector: &#39;my-app&#39;,\n  templateUrl: &#39;./app.component.html&#39;,\n  styleUrls: [ &#39;./app.component.css&#39; ]\n})\nexport class AppComponent  {\n  ipAddress:any;\n  constructor(private http: HttpClient){\n    this.http.get(&#39;https://jsonip.com&#39;)\n    .subscribe( data =&gt; {\n      this.ipAddress = data.ip;\n    })\n  }\n}</code></pre></div>\n<p>This should work now. Though the code editor is telling me that this line</p>\n<p>this.ipAddress = data.ip;</p>\n<p>is wrong.</p>\n<p>Looking at the official docs for the <a href=\"https://angular.io/guide/http\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">http client</a>, I need to tell the httpclient what the type response will be so  I will create an interface with just a ip property of string.</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">interface ItemsResponse {\nip: string;\n}</code></pre></div>\n<p>And add it like this</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">this.http.get&lt;ItemsResponse&gt;(&#39;https://jsonip.com&#39;)</code></pre></div>\n<p>That’s it.</p>\n<p>Thanks for reading.</p>\n<p>Here’s the stackblitz <a href=\"https://stackblitz.com/edit/angular-ipaddress?file=app%2Fapp.component.ts\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">demo</a></p>","fields":{"slug":"posts/angular-get-the-ip-address-of-the-user","tagSlugs":["/tag/angular/"]},"frontmatter":{"date":"2017-11-27T01:27:27.000Z","description":"In this short blog post, I will show you how to get the ip address of the user.","tags":["angular"],"title":"Angular - Get the ip address of the user"}}},"pageContext":{"slug":"posts/angular-get-the-ip-address-of-the-user"}},"staticQueryHashes":["251939775","401334301","4072520377"]}