<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>fetch data | Bogdan's blog</title>
	<atom:link href="https://blog.bogdancarpean.com/tag/fetch-data/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.bogdancarpean.com</link>
	<description>Code and anything else.</description>
	<lastBuildDate>Fri, 24 Jan 2020 18:45:16 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.1.1</generator>

<image>
	<url>https://blog.bogdancarpean.com/wp-content/uploads/2022/12/icons8-pencil-drawing-96.png</url>
	<title>fetch data | Bogdan's blog</title>
	<link>https://blog.bogdancarpean.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Fetch data needed on component&#8217;s template in Vue before render</title>
		<link>https://blog.bogdancarpean.com/fetch-data-needed-on-components-template-in-vue-before-render/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=fetch-data-needed-on-components-template-in-vue-before-render</link>
					<comments>https://blog.bogdancarpean.com/fetch-data-needed-on-components-template-in-vue-before-render/#respond</comments>
		
		<dc:creator><![CDATA[Bogdan]]></dc:creator>
		<pubDate>Thu, 01 Aug 2019 06:00:10 +0000</pubDate>
				<category><![CDATA[vuejs]]></category>
		<category><![CDATA[fetch data]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[router]]></category>
		<guid isPermaLink="false">http://blog.bogdancarpean.com/?p=311</guid>

					<description><![CDATA[<p>Let&#8217;s say in your Vue app you have a component that needs to fetch some data in order to display it on the template. This component needs this data on creation in order to be able to bind it on the template. Let&#8217;s take the following example: &#60;template&#62; &#60;div class="container"&#62; &#60;p&#62;Name: {{name}}&#60;/p&#62; &#60;p&#62;Age: {{age}}&#60;/p&#62; &#60;/div&#62; [&#8230;]</p>
The post <a href="https://blog.bogdancarpean.com/fetch-data-needed-on-components-template-in-vue-before-render/">Fetch data needed on component’s template in Vue before render</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></description>
										<content:encoded><![CDATA[<p>Let&#8217;s say in your Vue app you have a component that needs to fetch some data in order to display it on the template. This component needs this data on creation in order to be able to bind it on the template.</p>
<p>Let&#8217;s take the following example:</p>
<pre class="lang:default decode:true">&lt;template&gt;
  &lt;div class="container"&gt;
    &lt;p&gt;Name: {{name}}&lt;/p&gt;
    &lt;p&gt;Age: {{age}}&lt;/p&gt;
  &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
data():{
  return{
    name: null
    age: null
  }
}

created():{
  fetchUser().
    then(res =&gt; {
     this.name = res.data.name
     this.age = res.data.age 
    }
    )
}
&lt;/script&gt;</pre>
<p>In this example, we have a Vue Component that needs to fetch the user name and age before being able to create the template and display them. We use the lifecycle hook&nbsp;<em>created()&nbsp;</em>to fetch the data in the component. This will finally work, because of the reactive nature of Vue, but we are going to have an error in the console telling us that&nbsp;<em>name&nbsp;</em>is undefined. This happens because when we navigate to the component and this one gets rendered, the value of the variables is not yet fetched, the component rendering first the template, then executing the script. So we get the error on the console, then the script is run, data is fetched and displayed.</p>
<p>Let&#8217;s see how to do that without having the error on the console:</p>
<pre class="lang:default decode:true ">&lt;template&gt;
 &lt;div class="container" v-if="dataFetched"&gt;
   &lt;p&gt;Name: {{name}}&lt;/p&gt;
   &lt;p&gt;Age: {{age}}&lt;/p&gt;
 &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
data: {
  return {
    name: null
    age: null
    dataFetched: false
  }
},

beforeRouteEnter(to, from, next) {
  fetchUser().
    then(res =&gt; {
      next(vm =&gt; vm.setUser(res.data)
    })
},

methods: {
  setUser(user){
    this.name = user.name
    this.age = user.age
    this.dataFetched = true
  }
}
&lt;/script&gt;</pre>
<p>To achieve this, we first use the&nbsp;<em>beforeRouteEnter()&nbsp;</em>guard of the Vue Router that is called before the Router navigates to our component route. This guard has three parameters: to, from and next. From is an object containing the information about the route we are navigating from, also the parameters passed by route, to is the information about the route we are navigating to, next() is the function we call after we executed all we need on the guard to pursue the navigation.</p>
<p>But moving the fetch logic from the lifecycle hook to the guard alone won&#8217;t solve our problem because fetch is an asynchronous operation that will start on the guard, then next is called, leading to template rendering before data being fetched and virtually the same error on console.</p>
<p>To achieve this, we use a trick. We declare a boolean in the component, let&#8217;s say&nbsp;<em>dataFetched,&nbsp;</em>that we instantiate to false and we use it to trigger with&nbsp;<em>v-if&nbsp;</em>the render of the container div only when the data is fetched. We set the variable to true in the setUser method in the component after data is fetched, this way preventing the render of the template and the error on the console.</p>
<p>Happy coding!!!</p>The post <a href="https://blog.bogdancarpean.com/fetch-data-needed-on-components-template-in-vue-before-render/">Fetch data needed on component’s template in Vue before render</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.bogdancarpean.com/fetch-data-needed-on-components-template-in-vue-before-render/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Fetch data with the new HttpClient on Angular 5</title>
		<link>https://blog.bogdancarpean.com/fetch-data-with-the-new-httpclient-on-angular-5/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=fetch-data-with-the-new-httpclient-on-angular-5</link>
					<comments>https://blog.bogdancarpean.com/fetch-data-with-the-new-httpclient-on-angular-5/#respond</comments>
		
		<dc:creator><![CDATA[Bogdan]]></dc:creator>
		<pubDate>Sun, 10 Dec 2017 05:48:58 +0000</pubDate>
				<category><![CDATA[Angular 2]]></category>
		<category><![CDATA[@angular/common/http]]></category>
		<category><![CDATA[Angular 4]]></category>
		<category><![CDATA[Angular 5]]></category>
		<category><![CDATA[Angular service]]></category>
		<category><![CDATA[fetch data]]></category>
		<category><![CDATA[httpclient]]></category>
		<category><![CDATA[HttpClientModule]]></category>
		<category><![CDATA[injectable]]></category>
		<guid isPermaLink="false">http://blog.bogdancarpean.com/?p=121</guid>

					<description><![CDATA[<p>&#160; Note: given the semver adopted from now on by Angular team, I will refer to all versions of Angular2+ as Angular. For the old Angular 1.x, I will use AngularJs The new HttpClient on Angular 5 is here to replace the deprecating @angular/http module. The new HttpClientModule will be imported from @angular/common/http. For the purpose of this article, we are going to use [&#8230;]</p>
The post <a href="https://blog.bogdancarpean.com/fetch-data-with-the-new-httpclient-on-angular-5/">Fetch data with the new HttpClient on Angular 5</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></description>
										<content:encoded><![CDATA[<p>&nbsp;</p>
<p><strong>Note</strong>: <em>given the </em>semver<em> </em>adopted<em> from now on by </em>Angular<em> team, I will refer to all versions of Angular2+ as Angular. For the old Angular </em>1.x,<em> I will use AngularJs</em></p>
<p>The new HttpClient on Angular 5 is here to replace the deprecating @angular/http module.</p>
<p>The new HttpClientModule will be imported from @angular/common/http.</p>
<p>For the purpose of this article, we are going to use a service to fetch the data in which we are going to inject the new HttpClient. Our service is going to be injected into the component that is supposed to consume the data.</p>
<p>First, we need to import the HttpClientModule. We need to do this only once at the app.module level.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">...
import { HttpClientModule } from '@angular/common/http';

...
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ...,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }</pre>
<p>After that, we are going to inject the HttpClient into our service and to use it inside a get() function.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class FetchDataService {

  constructor(private _http: HttpClient) { }

  getUsers() {
    return this._http.get('https://yourapi/users');
  }

}</pre>
<p>The getUser() will return an Observable that we are going to treat in our consuming component.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Component, OnInit } from '@angular/core';
import { FetchDataService } from '../fetch-data.service';

@Component({
  selector: 'fetch-data',
  templateUrl: './fetch-data.component.html',
  styleUrls: ['./fetch-data.component.scss']
})
export class FetchDataComponent implements OnInit {

  constructor(private _fetchDataService: FetchDataService) { }

  data: any; //any here is just for demo purpose; please change with the type returned by your endpoint

  ngOnInit() {
     this._fetchDataService.getUsers().subscribe(
      data =&gt; { this.data = data},
      err =&gt; console.error(err)
     );
  }

}</pre>
<p>Since getUsers() returns an Observable, we call the subscribe() function to listen and process the returned data.</p>
<p>&nbsp;</p>
<p><em>If your company needs consulting on migration from Angular 1 to Angular 2/4/5 or training/update Angular knowledge, write me to <a href="mailto:contact@bogdancarpean.com">contact@bogdancarpean.com</a></em></p>The post <a href="https://blog.bogdancarpean.com/fetch-data-with-the-new-httpclient-on-angular-5/">Fetch data with the new HttpClient on Angular 5</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.bogdancarpean.com/fetch-data-with-the-new-httpclient-on-angular-5/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
