The ngOnInt lifecycle hook
is executed when the component is initialized, this event can be used to
initialize data required by the component. The most common use of this event is
to make ajax/api calls to fetch data required to be populated in the component.
We can also use this event to initialize properties of the component. This hook
gets executed after ngOnChanges()
and before any child components are initialized.
Let us see how this works with a simple example. In this example we use the ngOnInit() event to call a service method which uses an Observable to get API data from a service. The response data is stored in a userList object, which can be rendered in the component UI.
Let us see how this works with a simple example. In this example we use the ngOnInit() event to call a service method which uses an Observable to get API data from a service. The response data is stored in a userList object, which can be rendered in the component UI.
Angular component
import { Component } from '@angular/core';
import { UserdataService } from './userdata.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls:
['./app.component.css']
})
export class AppComponent {
userList;
errorMessage: string;
constructor(private svcData:
UserdataService) { }
ngOnInit() {
this.getData();
}
getData () {
this.svcData.getUsers ().subscribe(
data => this.userList =
data,
err => this.errorMessage
= err.status + ' - ' + err.statusText
);
}
}
Service to make API call
import { Injectable } from '@angular/core';
Service to make API call
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class UserdataService {
constructor(private http:
HttpClient) { }
getUsers() {
return
this.http.get('https://jsonplaceholder.typicode.com/users')
}
}
No comments:
Post a Comment