Monday, 8 May 2023

How to call API from angular

 Create a new service: Next, you need to create a new service. To create a new service, run the following command:

ng generate service my-service

Add functionality to the service: Open the my-service.service.ts file and add the functionality to the service. This can include making HTTP requests to a backend API, manipulating data, or performing other operations.





import { Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http';

@Injectable({

 providedIn: 'root',

})

export class MyServiceService {

 doSomething() {

   console.log('Doing something!');

 }

 constructor(private http: HttpClient) {}


 getData() {

   return this.http.get('https://jsonplaceholder.typicode.com/posts');

 }


}




Open the app.component.ts file and add the following code to inject the service:



import { Component } from '@angular/core';

import { MyServiceService } from './my-service.service';


@Component({

 selector: 'app-root',

 templateUrl: './app.component.html',

 styleUrls: ['./app.component.css'],

})

export class AppComponent {

 title = 'movie-app';

 data: any;


 constructor(private myService: MyServiceService) {}


 ngOnInit() {

   this.myService.getData().subscribe((data) => {

     this.data = data;

   });

 }

}




Open the my-component.component.html file and add the following code to display the data:

<h1>My Data:</h1>

<ul>

 <li *ngFor="let item of data">{{ item.title }}</li>

</ul>



Import the HttpClientModule: Open the app.module.ts file and add the following import statement at the top:

import { HttpClientModule } from '@angular/common/http';


Add HttpClientModule to the imports array: In the @NgModule decorator, add HttpClientModule to the imports array:


@NgModule({

  imports: [

    BrowserModule,

    HttpClientModule

  ],

  declarations: [AppComponent],

  bootstrap: [AppComponent]

})

export class AppModule { }



No comments:

Post a Comment